update_option in javascript

时间:2013-06-04 作者:John Timson Rimeišis

因此,wordpress中有一个功能可以将命名选项/值对更新到选项数据库表中:<?php update_option( $option, $new_value ); ?>. 我正试图用javascript实现这个功能,这样当你点击页面底部时,一个选项就会更新。我使用此脚本检查您何时点击页面底部:

$(window).scroll(function () {
   if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
      /***update options***/
   }
});
所以我的问题是如何在javascript中实现update\\u option函数。

1 个回复
最合适的回答,由SO网友:Marc Dingena 整理而成

JavaScript

$(window).scroll(function () {
    if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
        /***update options***/
        $.ajax({
            type:   \'POST\',
            url:    \'http://www.example.com/wp-admin/admin-ajax.php\',
            data:   {
                action    : \'hit-bottom\',
                option    : $option, // your option variable
                new_value : $new_value // your new value variable
            },
            dataType: \'json\'
        }).done(function( json ) {
            alert( "Ajax call succeeded, let\'s see what the response was." );
            if( json.success ) {
                alert( "Function executed successfully and returned: " + json.message );
            } else if( !json.success ) {
                alert( "Function failed and returned: " + json.message );
            }
        }).fail(function() {
            alert( "The Ajax call itself failed." );
        }).always(function() {
            alert( "This message is always displayed, whether the call failed or succeeded." );
        });
    }
});

functions.php

/* hit bottom of screen event  */
add_action( \'wp_ajax_hit-bottom\', \'wpse_hit_bottom\' );
add_action( \'wp_ajax_nopriv_hit-bottom\', \'wpse_hit_bottom\' );
function wpse_hit_bottom() {
    $option = $_POST[\'option\'];
    $new_value = $_POST[\'new_value\'];

    if( !isset( $option ) || $option == \'\' || !isset( $new_value ) || $new_value = \'\' ) {
        die(
            json_encode(
                array(
                    \'success\' => false,
                    \'message\' => \'Missing required information.\'
                )
            )
        );
    }

    update_option( $option, $new_value );
    die(
        json_encode(
            array(
                \'success\' => true,
                \'message\' => \'Database updated successfully.\'
            )
        )
    );
}
结束

相关推荐

如何每页一次将某些javascript源代码入队

我需要我的插件生成以下内容-每页一次:<script type=\"text/javascript\" src=\"https://<ritc url for js file>\"></script> <script type=\"text/javascript\"> ritc.initialize(\'63864593a4153879\'); </script> 这样做的目的是允许一个或多个短代码(所有短代码都