2016-01-06 56 views
0

我想每30秒更新一个WordPress小部件中的信息。所以我想我最好使用一些Ajax。如何在WordPress中定期使用jQuery调用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秒就开一次?

非常感谢!

+1

看一看这个http://stackoverflow.com/questions/2170923/whats-the-easiest-way-to-call-a-function-every-5-seconds-in-jquery – Enrico

+0

谢谢您。是的......这与我所遇到的问题一样,并且在那里解决了。 –

回答

3

您需要使用setInterval函数。 仅供参考:如果您需要在30秒后只提升一次ajax呼叫,您需要使用setTimeout等待30秒,然后再运行一次。

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

谢谢!这工作:-) –

+0

不客气! – erikscandola