所以我每隔5秒就通过POST使用ajax检索一些数据,我想要实现的是如果php文件输出一些东西,然后以某种方式停止setInterval或将其设置为9999999。
以下是我尝试的内容:
var interval = DEFINEDFROMMYQL;
$(function() {
setInterval(function() {
$.ajax({
type: "POST",
url: "url/file.php",
data: "whatever=2",
success: function(html) {
$("#new").html(html);
if(html.lenght > 0) {
var interval = 99999999999999;
}
}
});
}, interval);
});
我是新手,所以任何帮助都会受到赞赏。
答案 0 :(得分:1)
您可以使用clearInterval()停止setInterval
启动的计时器,并将拼写错误 html.lenght
更正为html.length
// var interval = DEFINEDFROMMYQL;
$(function() {
yourInterval = setInterval(function() {
$.ajax({
type: "POST",
url: "url/file.php",
data: "whatever=2",
success: function(html) {
$("#new").html(html);
if(html.length > 0) {
///var interval = 99999999999999;
clearInterval(yourInterval);
}
}
});
}, interval);
});
答案 1 :(得分:1)
您可以通过几种不同的方式处理这个问题,但是根据您的问题(“以某种方式停止setinterval”),让我们将实现切换到setTimeout
,并将代码重构为我们可以回忆的函数。所以......
var interval = DEFINEDFROMMYQL;
$(function() {
// establish a function we can recall
function getDataFromServer(){
// this encapsulates the original code in a function we can re-call
// in a setTimeout later on (when applicable)
$.ajax({
type: "POST",
url: "url/file.php",
data: "whatever=2",
success: function(html) {
$("#new").html(html);
// only if the length is 0 do we re-queue the function
// otherwise (becase it's setTimeout) it will just die
// off and stop.
if(html.lenght == 0) {
setTimeout(getDataFromServer, interval);
}
}
});
}
// make an initial call to the function to get the ball rolling
setTimeout(getDataFromServer, interval);
// if you want it to execute immediately instead of wait out the interval,
// replace the above line to simply:
//getDataFromServer();
});