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

Mis*_*yng 1 javascript ajax wordpress jquery

我想每 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
}
Run Code Online (Sandbox Code Playgroud)

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

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

非常感谢!

eri*_*ola 5

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

setInterval(function(){
    jQuery.post(ajaxurl, data, function(response) {
        alert(response);
    });
}, 30000);
Run Code Online (Sandbox Code Playgroud)