AJAX: sending xmlhttp requests in a loop ... but all the responses are not received
I have this function below and I call that function in a loop I get the alert n times but only n-1 or sometimes n-2 responses
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==4 && xmlhttp.status==200)
{
a开发者_JAVA技巧lert(xmlhttp.responseText);
//document.getElementById("warnings_panel").innerHTML+=xmlhttp.responseText;
}
}
alert("in ajax)
xmlhttp.open("GET","getresponse.php?start="+ start
+ "&end=" + end,true);
xmlhttp.send();
You appear to be depending on a single global xmlhttp
variable. Don't do that.
Make sure you are sending something unique with each request. IE sometimes caches AJAX request responses - if you append something unique to your query (such as a counter that increments with each request), it will prevent IE from returning the cached response.
When you are using loop to send ajax request and using a single object, there is a possibility that the second or concecutive request can be sent even before the response for the first request is sent..
So use individual objects to send individual requests..
The sample code should be like this..
for(i=0; i<10; i++){
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
eval("xmlhttp"+i+"=new XMLHttpRequest()");
}
else
{// code for IE6, IE5
}
eval("xmlhttp"+i+".onreadystatechange=function(i)");
function(var obj)
{
//function contents
}
alert("in ajax)
// assign responsetext and send code
}
xmlhttp.open("GET","getresponse.php?start="+ start
+ "&end=" + end,true);
In the above line you have mentioned true as the last parameter instead of that use false.
So the AJAX becomes a synchronous call, the interprter will wait till the responses arrives.
But for every response check for null.
<html>
<body>
</body>
<script type="text/javascript" defer>
function ajaxping() {
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==4)
{
var status = xmlhttp.status;
var isSuccess = status >= 200 && status < 300 || status === 1223 || status === 304;
if(isSuccess) {
alert("got success response");
}
}
}
alert("in ajax");
xmlhttp.open("GET","test.html");
xmlhttp.send();
}
var func = function() {
for(var i=0;i<10;i++){
ajaxping();
}
}
func();
</script>
</html>
精彩评论