Ajax重新发送XMLHttpRequest [英] Ajax resending XMLHttpRequest
问题描述
我有一个这样的客户端js/ajax脚本:
I've got a client side js/ajax script like this:
<p>server time is: <strong id="stime">Please wait...</strong></p>
<script>
function updateAjax() {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==3 && xmlhttp.status==200) {
document.getElementById("stime").innerHTML=
xmlhttp.responseText;
}
if (xmlhttp.readyState==4) {
xmlhttp.open("GET","date-sleep.php",true);
xmlhttp.send();
}
}
xmlhttp.open("GET","date-sleep.php",true);
xmlhttp.send();
}
window.setTimeout("updateAjax();",100);
</script>
在服务器端还有一个:
<?php
echo 6;
for ($i=0; $i<10; $i++) {
echo $i;
ob_flush(); flush();
sleep(1);
}
?>
在第一次打开"并发送"之后,它可以正常工作,但是当服务器完成脚本并且 xmlhttp.readyState == 4
时,xmlhttp重新发送请求,但是什么也没有发生.>
After first 'open' and 'send' it works ok, but when the server finishes the script and xmlhttp.readyState == 4
then the xmlhttp resends the request but nothing happens.
推荐答案
而不是一直重复使用同一XHR对象,请尝试使用一个新对象重复该功能.至少应该可以解决您列出的不兼容问题.
Instead of re-using the same XHR object all the time, try repeating the function with a new object. This should at least fix incompatibility issues as you listed.
如果要无限循环,请尝试在其回调内重新调用Ajax函数.
Try re-calling your Ajax function inside the callback of it, if you want to loop it infinitely.
if (xmlhttp.readyState==4) {
updateAjax(); //or setTimeout("updateAjax();",100); if you want a delay
}
我还建议您将 .innerHTML
方法放入 .status == 200
表示成功.像这样:
I'd also suggest putting your .innerHTML
method inside the .readyState==4
, which is when the requested document has completely loaded, and .status==200
which means success. Like this:
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("stime").innerHTML=
xmlhttp.responseText;
updateAjax(); //or setTimeout("updateAjax();",100);
}
此外,如果您希望跨浏览器使用Ajax,则应测试浏览器是否支持 XHR您正在使用的对象:
Also, if you want your Ajax to be cross-browser, you should test if the browser supports the XHR object which you're using:
var xmlhttp = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
我刚刚键入了上面的代码,但是它可以很好地添加与IE和其他浏览器的较早版本的兼容性.
I just typed the code above but it should work just fine to add compatibility with older versions of IE and other browsers.
这篇关于Ajax重新发送XMLHttpRequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!