Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

readystatechange using addEventListener versus old-style property?

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?

like image 943
Delan Azabani Avatar asked Aug 07 '11 06:08

Delan Azabani


People also ask

What is the difference between onload and Onreadystatechange?

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.

What is readystatechange event?

The readystatechange event is fired when the readyState attribute of a document has changed. This event is not cancelable and does not bubble.

What is Readystatechange in JavaScript?

readyState property describes the loading state of the document . When the value of this property changes, a readystatechange event fires on the document object.

What is the use of addEventListener in JavaScript?

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.


2 Answers

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.

like image 160
dtech Avatar answered Sep 20 '22 12:09

dtech


This worked for me.

xhr.addEventListener('readystatechange', evt => {
    if (this.readyState == 4 && this.status == 200) {
        console.log(this.responseText);
        return this.responseText;
    }
}, false);
like image 43
jantje19 Avatar answered Sep 20 '22 12:09

jantje19