views:

183

answers:

1

I'm running into a strange problem. In the following sample code, if I set asynchronous to true the request fails and Chrome tells me 'failed to load resource'. However, if I switch it to synchronous it goes through fine.

Additionally, if I do multiple xhr requests using this code and its set to async, all requests exhibit the same problem, but the last one is successful. If I set the xhr to synchronous (i.e. false) then all requests go through fine.

To all who will say, 'Just use jQuery', this is for a project that needs to run independently of any libraries. I love jQuery, but not for this.

I am testing this in Chrome6.0.458.1 and Firefox 3.6.4. Here's the code:

    var xhr = window.XMLHttpRequest?
        new XMLHttpRequest():
        new ActiveXObject('Microsoft.XMLHTTP');

    var doxhr = function(url,cb){
        xhr.open('get',url,true);
        xhr.onreadystatechange = function(ev){
            console.log(xhr.readyState, xhr.status );
            //if(xhr.readyState === 4 && xhr.status === 200){
            //  cb(xhr.responseText);
            //}
        }
        xhr.send(null);
    }
+3  A: 

I'm not sure the two problems are related, but if you plan on making multiple XHR requests, you shouldn't reuse the same XHR for each request or you should build a queuing system to stop later requests from stomping the earlier requests. You can probably solve the problem of only the last request completing successfully by wrapping your xhr inside doxhr():

var doxhr = function(url,cb){
    var xhr = window.XMLHttpRequest?
        new XMLHttpRequest():
        new ActiveXObject('Microsoft.XMLHTTP');
        xhr.open('get',url,true);
    xhr.onreadystatechange = function(ev){
        console.log(xhr.readyState, xhr.status );
        //if(xhr.readyState === 4 && xhr.status === 200){
        //  cb(xhr.responseText);
        //}
    }
    xhr.send(null);
}
Andrew
I'm such a fool. Literally 10 seconds before I refreshed the page to see your answer I just realized what I was doing. In fact I WAS declaring a single xhr var outside of the function. I just remembered you have to create a new XMLHttpRequest object for each request.
Geuis
Ha. I've done that myself more times than I should. I'm actually pretty partial to queuing systems myself. Most browsers are configured to have four active requests at a time, so if you chain your requests while requesting other page elements (like images) your XHR can cause your page to appear stalled. If you use a "Singleton" that allocates two XHR objects and uses them in tandem (so, is that a Doubleton?), you can reserve 50% of the browser request pool for other resources.
Andrew