我想在每10秒后调用一个php函数,为此我使用javascript setInterval。
使用setInterval来调用服务器进程从来都不是一个好主意。当服务器得到下一个调用时,在它返回一些东西之前,它可能还没有完成工作。
由于我们有Ajax,我们可以使用回调来重新发出调用。
例如在jQuery中—该技术在XMLHttpRequest的readystate更改中是相同的
function callServer() {
$.get("myserverprocess.php",function(data) {
$("#somecontainer").html(data);
setTimeout(callServer,10000);
});
}
注意:如果上面的操作失败,将不会再尝试。如果需要再试一次,请使用
function callServer() {
$.ajax({
url: "myserverprocess.php",
type: 'get'
})
.done(function(data) {
$("#somecontainer").html(data);
})
.always(function() {
setTimeout(callServer,10000);
})
.fail(function() {
$("#somecontainer").html("Error");
});
}
在纯JS中:
function callServer() {
var x = new XMLHttpRequest();
x.open("GET", "myserverprocess.php", true);
x.onreadystatechange = function() {
if (x.readyState==4 && x.status==200) { // remove status test to keep calling
document.getElementById("someontainer").innerHTML=x.responseText
setTimeout(callServer,10000);
}
x.send();
}
假设您有script.php,其中运行PHP函数。客户端:
var working = false;
setInterval(ajaxCall, 10000); //10000 MS == 10 seconds
function ajaxCall() {
if(working)
return;
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
working = false;
if(xmlhttp.status == 200){
console.log(xmlhttp.responseText);
}
}
}
xmlhttp.open("POST", "script.php", true);
xmlhttp.send();
working = true;
}
看到一个重复的问题(我拿了上面的代码):如何在jquery中设置ajax调用间隔[closed]和jquery -less ajax调用