开发者

readystatechange using addEventListener versus old-style property?

开发者 https://www.devze.com 2023-03-26 16:06 出处:网络
readystatechange is a standard event for XMLHttpRequest objects, and so should be able to have functions listen on the event either using

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() { .开发者_C百科.. }, 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?


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消