最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - readystatechange using addEventListener versus old-style property? - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question asked Aug 7, 2011 at 6:56 Delan AzabaniDelan Azabani 81.4k30 gold badges172 silver badges212 bronze badges 1
  • 1 It is at least defined in the W3C spec: w3.org/TR/XMLHttpRequest/#event-handler-attributes – Felix Kling Commented Aug 7, 2011 at 7:09
Add a comment  | 

2 Answers 2

Reset to default 12

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)

  1. 暂无评论