Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top