readystatechange
is a standard event for XMLHttpRequest
objects, and so should be able to have functions listen on the event either using
r.onreadystatechange = function() { ... };
as well as
r.addEventListener('readystatechange', function() { ... }, false);
However, the latter method only seems to work in Firefox and Chrome, but not Opera, which does not throw an error but simply has no effect. Why is this, and is this even correct behaviour?
A readystatechange occurs several times in the life of a request as it progresses to different phases, but a load event only occurs when the request has successfully completed. If you're not interested in detecting intermediate states or errors, then onload might be a good choice.
The readystatechange event is fired when the readyState attribute of a document has changed. This event is not cancelable and does not bubble.
readyState property describes the loading state of the document . When the value of this property changes, a readystatechange event fires on the document object.
The addEventListener() method makes it easier to control how the event reacts to bubbling. When using the addEventListener() method, the JavaScript is separated from the HTML markup, for better readability and allows you to add event listeners even when you do not control the HTML markup.
The MDN docs on XMLHttpRequest don't specifically mention raising a readystatechange
event, but the W3C docs do require it.
That combined with the general rule "onxxx
is the event handler for event xxx
" would imply that the Opera behaviour is incorrect.
This worked for me.
xhr.addEventListener('readystatechange', evt => {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
return this.responseText;
}
}, false);
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