【问题标题】:How to call Ajax with jQuery periodically in WordPress?如何在 WordPress 中定期使用 jQuery 调用 Ajax?
【发布时间】:2016-04-10 21:03:16
【问题描述】:

我想每 30 秒更新一次 WordPress 小部件中的信息。因此,我认为我最好使用一些 Ajax。

我在WordPress Codex 上找到了这个并将其添加到我的functions.php 中:

add_action( 'admin_footer', 'my_action_javascript' ); // Write our JS below here

function my_action_javascript() { ?>
<script type="text/javascript" >
jQuery(document).ready(function($) {

    var data = {
               'action': 'my_action',
               'whatever': 1234
    };

    // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
    jQuery.post(ajaxurl, data, function(response) {
        alert(response);
    });
});
</script> <?php
}

add_action( 'wp_ajax_my_action', 'my_action_callback' );

    function my_action_callback() {
    global $wpdb; // this is how you get access to the database
    $bla = get_option("airtime_now_playing");
    echo $bla;
    wp_die(); // this is required to terminate immediately and return a proper response
}

它工作正常并且确实检索到我需要的东西。

我怎样才能不只触发一次,而是每 30 秒触发一次?

非常感谢!

【问题讨论】:

标签: javascript jquery ajax wordpress


【解决方案1】:

您需要使用setInterval 函数。 仅供参考:如果您只需要在 30 秒后引发一次 ajax 调用,则需要使用 setTimeout 等待 30 秒然后执行一次。

setInterval(function(){
    jQuery.post(ajaxurl, data, function(response) {
        alert(response);
    });
}, 30000);

【讨论】:

    猜你喜欢
    • 2017-09-19
    • 2012-06-04
    • 1970-01-01
    • 1970-01-01
    • 2011-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多