Can one replace xhr.onreadystatechange with xhr.onload for AJAX calls?
JavascriptAjaxXmlhttprequestJavascript Problem Overview
I need to support major modern browsers only (IE10+, FF, Chrome, Safari)
Can I make this substitution as I want to simplify my code base:
From:
xhr.onreadystatechange = function () {
if (this.readyState === 4) {
if (this.status === 200) {
o.callback(xhr.responseText);
} else {
return false;
}
} else {
return false;
}
};
To:
xhr.onload = function (test) {
o.callback(xhr.responseText);
};
I don't feel that the MDN documentation is clear in this regard.
Clarification:
I choose not to use a framework.
Javascript Solutions
Solution 1 - Javascript
maybe you take a look at this one and a look at W3C: XMLHttpRequest it's the same if your browser supports xhr.onload. Requires XMLHttpRequest 2)
You can also write a wrapping function that emulates xhr.onload if it's not present.
(I think you need to override XMLHttpRequest.prototype.onload = function(args){//calling onreadystatechanges somehow}
). If you only support modern browsers using xhr.onload should be available - the best solution is using a framework (like [tag:jquery] or [tag:mootools] that provides wrapping functionality for that.
Solution 2 - Javascript
In the MDN documentation they state the following
> Events > > onreadystatechange as a property on the xhr object is supported in all > browsers. > > Since then, a number of additional event handlers were implemented in > various browsers (onload, onerror, onprogress, etc.). These are > supported in Firefox. In particular, see nsIXMLHttpRequestEventTarget > and Using XMLHttpRequest. > > More recent browsers, including Firefox, also support listening to the > XMLHttpRequest events via standard addEventListener APIs in addition > to setting on* properties to a handler function.
So I think you can assume that onreadystatechange is the way to go and onload is a addition that can be used if the browser supports it. @mr.VVoo answer is the correct one, to stick to w3c when in doubt.
Solution 3 - Javascript
Since the original asker said "I need to support major modern browsers only (IE10+, FF, Chrome, Safari)" it is obvious that onload
, onerror
, etc are the ways to go. Also, as of today, onreadystatechange
is pretty much obsolete, as you are obviously not going to support anything that old that it supports onreadystatechange
only.
To sum it up, forget about onreadystatechange
.
Solution 4 - Javascript
You can clean up your first example by doing this
xhr.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
o.callback(xhr.responseText);
} else {
return false;
}
};
Note, you probably want to check onload
too with this.status === 200
if you are doing something with the else statement. Although, if you are checking for errors, there is also onerror
, which you can write something like
xhr.onerror = function(){
console.log('Error: Do something else...');
}