jQuery - 每 10 秒调用一次 ajax [英] 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.
所以我构造了这个:
$(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);
或者:
setInterval(get_fb, 10000);
或者,如果您希望它仅在成功完成调用后运行,您可以在您的 .ajax().success()
回调中进行设置:
Or, if you want it to run only after successfully completing the call, you can set it up in your .ajax().success()
callback:
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);
}
或者使用 .ajax().complete()
如果你想让它运行而不管结果:
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 - 每 10 秒调用一次 ajax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!