Problem description: Hello!
My XMLHTTPRequest object, when ready, does a couple of things. The responseText which I receive is split up, and sent as a parameter to myFunction()
.
Now, I need to call myFunction()
'n' number of times, with substrings of the response text as parameters.
This Works:
myAjaxObj.onreadystatechange=function()
{
if(myAjaxObj.readyState==4)
{
if(myAjaxObj.status==200)
{
myFunction( myAjaxObj.responseText, id )
This DOESN'T Work:
myAjaxObj.onreadystatechange=function() 开发者_运维百科
{
if(myAjaxObj.readyState==4)
{
if(myAjaxObj.status==200)
{
var count i=0;
for( i=0; i < 5; i++ )
{
[b]alert("Without this it wont work") [/b]
myFunction( myAjaxObj.responseText, i );
}
Basically, the code within the for-loop won't run, unless the alert() is uncommented. I've read somewhere about javascript closures, and the facts that it kinda gives the execution/rendering to get in sync
What would be the solution?
OK, this is happening because you are not polling your onreadystatechange function. Basically, the call is asynchronous and you need to poll your readyState variable every few milliseconds to see when it changes. This is the reason it is working with the alert() - the alert is causing a long pause during which the AJAX response is recieved by the client. The readyState variable is checked after the alert has got a response and your code executes as needed.
However, without the alert(), your code checks for the readyState variable just once
One way around is to make the call synchronous by setting the asynchronous parameter to false in the call. This has a downside that the client will freeze until the AJAX response is received.
Another way is to keep polling the readyState variable.
Basically, you should not trust the callback function to execute itself properly - it gets stuck many times!
精彩评论