我的论坛上有一个页面,我试图在有新帖子时自动更新该页面,但是它似乎只能间歇性地工作。
我有一种感觉,那就是成功和等待的顺序,但是我一生都无法解决,难道是一个更懂行的人看到我要去哪里了吗?
谢谢
<script>
var timestamp = Math.round((new Date()).getTime() / 1000);
function myTimer() {
$.ajax({
url: 'loadtopic.php?id=<? echo $getid; ?>&time=' + timestamp,
success: function(data) {
$("#append").before(data);
setTimeout(myTimer,3000);
timestamp = Math.round((new Date()).getTime() / 1000);
}
});
}
myTimer();
</script>
如果请求由于任何原因而失败,则不会调用成功,因此循环将中断。您可以使用setInterval来确保它被调用。
<script>
var timestamp = Math.round((new Date()).getTime() / 1000);
function myTimer() {
$.ajax({
url: 'loadtopic.php?id=<? echo $getid; ?>&time=' + timestamp,
success: function(data) {
$("#append").before(data);
timestamp = Math.round((new Date()).getTime() / 1000);
}
});
}
myTimer();
setInterval(myTimer,3000);
</script>
否则,将setTimeout置于“ complete”选项中,即使请求失败,代码也将被执行。
<script>
var timestamp = Math.round((new Date()).getTime() / 1000);
function myTimer() {
$.ajax({
url: 'loadtopic.php?id=<? echo $getid; ?>&time=' + timestamp,
success: function(data) {
$("#append").before(data);
timestamp = Math.round((new Date()).getTime() / 1000);
},
complete: function() {
setTimeout(myTimer,3000);
}
});
}
myTimer();
</script>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句