如何在WordPress中使用jQuery定期调用Ajax

How to call Ajax with jQuery periodically in WordPress?

本文关键字:jQuery 调用 Ajax WordPress      更新时间:2023-09-26

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

我在WordPress Codex上找到了这个,并将其添加到我的函数中。hp:

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秒发射一次?

非常感谢!

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

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