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 jquery or mootools that provides wrapping functionality for that.
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.
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
.
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...');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With