简体   繁体   中英

My onReadyStateChange is never called,why?

my code is simple.

function useXMLHttpRequest() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "test.ashx", false);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
xmlhttp.onReadyStateChange = function () {
    alert("ss");
};
xmlhttp.send("i=5");
alert(xmlhttp.responseText);

}

when I call useXMLHttpRequest.Yes ,it alerts the xmlhttp.responseText's value. but it doesn't alert("ss"). Both in IE9 and firefox. Anyone can tell me what's worng?

JavaScript (and all other languages that I know of) are case-sensitive, so onreadystatechange is not the same as onReadyStateChange .

Try this instead:

xmlhttp.onreadystatechange = function() {
    alert("ss");
};

You have

xmlhttp.open("POST", "test.ashx", false);

3rd parameter is false , which means that you are using synchronous request. For such requests onreadystatechange does not work and is discouraged to use it. Anyway, your request will not go further until complete completion, so alert(xmlhttp.responseText); immediately after xmlhttp.send("i=5"); works correctly and there is no need to handle request state change event.

See more here and here .

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