jQuery的 - AJAX调用每10秒 [英] jQuery - Call ajax every 10 seconds
问题描述
我有这样构成一个MySQL数据库反馈:
I have a mysql feedback database constructed like this:
名称|位置|反馈
莱恩|英格兰|大力支持
Ryan | England | great support
显然有比这更多的条目。我想建立一个反馈DIV,它通过AJAX显示一个新的反馈产品,每10秒。
Obviously there's more entries than that. I am trying to build a feedback div, where it displays a new feedback item every 10 seconds via ajax.
所以,我已经建造这样的:
So I have constructed this:
$(document).ready(function(){
new get_fb();
});
function get_fb(){
var feedback = $.ajax({//Ajax
type: "POST",
url: "feedback.php",
async: false
}).responseText;//end of ajax
$('div.feedback-box').html(feedback).delay(10000).queue(function() {
new get_fb();
});
}
这是我的PHP文件:
And here's my PHP file:
$result = mysql_query("SELECT * FROM feedback ORDER BY RAND() LIMIT 0,1");
while($row = mysql_fetch_array($result))
{
$name = $row['name'];
$location = $row['location'];
$feedback = $row['feedback'];
echo "
<p>Name: $name, Location: $location, Feedback: $feedback.</p>
";
}
不过,这只能说明两种。它不保留表示新的,它纯粹示出了第一,然后在第二和停止。
However, this only shows two. It doesn't keep showing new ones, it purely shows the first then the second and stops.
我是什么做错了吗?感谢:)
What am I doing wrong? Thanks :)
推荐答案
你要想做一个的setInterval()
?
setInterval(function(){get_fb();}, 10000);
或者,如果你想让它运行后,才成功地完成呼叫,您可以将它设置在阿贾克斯()成功()
回调:
function get_fb(){
var feedback = $.ajax({
type: "POST",
url: "feedback.php",
async: false
}).success(function(){
setTimeout(function(){get_fb();}, 10000);
}).responseText;
$('div.feedback-box').html(feedback);
}
或者使用阿贾克斯()完成()
如果你想让它不管结果运行:
Or use .ajax().complete()
if you want it to run regardless of result:
function get_fb(){
var feedback = $.ajax({
type: "POST",
url: "feedback.php",
async: false
}).complete(function(){
setTimeout(function(){get_fb();}, 10000);
}).responseText;
$('div.feedback-box').html(feedback);
}
下面是两者的示范。请注意,成功的作品只有一次,因为的jsfiddle是在Ajax调用返回404错误。
Here is a demonstration of the two. Note, the success works only once because jsfiddle is returning a 404 error on the ajax call.
这篇关于jQuery的 - AJAX调用每10秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!