To get the response, add a readystatechange
event handler function. This will get called back when the response is ready to read:
xhr.onreadystatechange= function() {
if (this.readyState!==4) return; // not ready yet
if (this.status===200) { // HTTP 200 OK
alert(this.responseText);
} else {
// server returned an error. Do something with it or ignore it
}
};
xhr.open('GET', 'http://www.example.net/abc.aspx', true);
xhr.send();
Incidentally:
("XMLHttpRequest" in window)
Whilst in
is in general a good way to test whether a property exists, this is one of the very few places where it's not ideal.
The problem is that in IE7+, when the ‘native XMLHttpRequest’ option is turned off, XMLHttpRequest
still exists as a property in window
, but with the unusable value null
. So it's better in this specific case to use a simple truth test, which will allow fallback to ActiveX in the (unlikely) event that this option is disabled:
var xhr= window.XMLHttpRequest? new XMLHttpRequest() : new ActiveXObject('MSXML2.XMLHttp');