简体   繁体   中英

Chrome XMLHttpRequest readyState===4 returns empty responseText

I'm having a problem where httpReq.responseText is empty after readyState is 4 in Chrome (Version 33.0.1750.149 m). When I debug through and stop on the console.log(url) line, readyState is an empty string, and looking in the Network tab, chrome shows an empty response in the "Response" section for the url. Nothing surprising there.

What's surprising is that as soon as I let the javascript continue from that breakpoint, the Network tab populates the response section. I know for certain my server is returning data, and the url is from the same domain (localhost). When I tested in firefox, it works fine.

My code looks like this:

    var httpReq = new XMLHttpRequest();

    httpReq.onreadystatechange = function() {
        if( httpReq.readyState === 4 ) {
            if( httpReq.status === 200 ) {
                console.log(url)
                result.return(httpReq.responseText)
            } else {
                if(!result.isResolved)
                    result.throw(new Error('Error in request'))
            }
        }
    }

    httpReq.open('GET', url, true);
    httpReq.send(null);

Any ideas what might be going on?

Update : if I change the .open call to httpReq.open('GET', url, false); it works. Something must be going wrong with the onreadystatechange function - is this a bug in chrome?

Update : I made a minimal repro of this. I have two separate ajax functions in my code (one from a module I don't control). One of them seems to be doing a synchronous http request. Here's a repro:

var url = '/'
var httpReq = new XMLHttpRequest();
var httpReq2 = new XMLHttpRequest();

httpReq.onreadystatechange = function() {
    console.log('a '+httpReq.readyState+":"+httpReq.status+' - '+httpReq.responseText.substring(0,40))
};
httpReq2.onreadystatechange = function() {
    console.log('b '+httpReq.readyState+":"+httpReq.status+' - '+httpReq.responseText.substring(0,40))
};

httpReq.open('GET', url ); // asynchronous *first*
httpReq.send();
httpReq2.open('GET', url, false); // synchronous *second*
httpReq2.send();

Its pretty clear to me now that this is a bug in chrome. I'll file a ticket with them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM