Ajax won't get past readyState 1, why?

六眼飞鱼酱① 提交于 2019-11-27 02:53:02

问题


I'm trying to get this function to work, which does a request for parameter url then sends the responseText to callback which is a function.

It seems that it only gets to readyState 1 (thanks to the Firebug commands).

Here it is:

function Request(url, callback){
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
} else{
    return false;
}
httpRequest.onreadystatechange = function(){
    console.log(httpRequest.readyState);
    if (httpRequest.readyState == 4) {
        callback(httpRequest.responseText);
    }
};
console.log(httpRequest, url);
httpRequest.open('GET', url, true);
httpRequest.send(null);
}

回答1:


I workarounded this problem assigning onload event instead of onreadystatechange:

function Request(url, callback){
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
} else{
        return false;
}

var readyStateChange = function(){
    console.log(httpRequest.readyState);

    if (httpRequest.readyState == 4) {
                callback(httpRequest.responseText);
    }
};


if (isFirefox && firefoxVersion > 3) {
    httpRequest.onload = readyStateChange;
} else {
    httpRequest.onreadystatechange = readyStateChange;
}

console.log(httpRequest, url);
httpRequest.open('GET', url, true);
httpRequest.send(null);
}



回答2:


Check that the URL in question does actually respond by visiting it directly in the browser.

Test with a different browser do you get the same result.

Use some form of HTTP monitor to watch the client to server conversation (my favorite is Fiddler)




回答3:


Possibly the Ajax request doesn't return data (so, a server side error of some kind). Try enabling the option 'show XMLHttpRequests' in the firebug console, to check for this.




回答4:


I also faced the same issue. By reading the url below, I got mine solved.

http://bytes.com/topic/javascript/answers/548442-ajax-readystate-1-wall

basically, when I assign my function as the event listener for httpRequest.onreadystatechange, I cannot pass any variable to it. SO that I have to embed the variable inside the HTTP POST string to the server backend then get it back from the HTTP response.

It works fine for FF 3. No need to use jQuery.




回答5:


I had the same problem on FireFox but not on Chrome.

The problem was my response had the mime-type set to "application/octet-stream".

Changing it to "text/html" made it work on FireFox too.



来源:https://stackoverflow.com/questions/751269/ajax-wont-get-past-readystate-1-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!