roast_soul
roast_soul

Reputation: 3650

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?

Upvotes: 0

Views: 1160

Answers (2)

bhovhannes
bhovhannes

Reputation: 5679

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.

Upvotes: 0

Blender
Blender

Reputation: 298106

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");
};

Upvotes: 3

Related Questions