I'm using the following ajax function:
function callAjax(request,callback)
{
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)
{
if(callback != null)callback(xmlhtt开发者_高级运维p.responseText);
}
}
xmlhttp.open("GET",request,true);
xmlhttp.send();
}
And I've found that when I call this function 3 or more times in sequence, some of the callbacks are sometimes not executed. The ajax request occurs, and a result is returned, but somehow the callback function does not get called. Worse, this doesn't even happen consistently - sometimes it works, sometimes not. What I want to know is, why? And more importantly, how can I fix it? As far as I can tell, the callbacks will be run if there is at least a 4 millisecond gap between them. If two of the pages return within that timeframe, only one of them (the second I believe, but I'm not sure it always is) will actually be handled.
I know I can work around this by making sure that I'm only waiting for one ajax request to return at a time (through liberal use of sleep()). However, this slows down the page significantly; I want to be able to fire off all three (or more) requests, and have them execute their callbacks whenever they return.
What am I doing wrong? How do I make it work?
NB: I'm not looking for someone to say 'oh, you should use jquery'. I do not want to use any external libraries for this - please just tell me how to fix the code I have.
xmlhttp
is a global variable so it will be overwritten if you have more than one call happening at the same time.
You are also using a GET request. GET requests get cached if the improper heading are not set. See "heartbeat" logger qustion for details on how to avoid caching.
Most likely the status is not 200. Your callback will only happen for status 200 in you current code.
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
if(typeof callback == 'function')
callback.call(xmlhttp, xmlhttp.responseText);
}
else{
alert("status is " + xmlhttp.status);
}
}
Could be a page caching issue, which you can simply fix by adding a random number variable to your request.
Also, If I'm not mistaken, browsers do have a maximum number of simultaneous ajax requests at once.
精彩评论