javascript 使用 addEventListener 与旧式属性的 readystatechange?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6971259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 22:31:45  来源:igfitidea点击:

readystatechange using addEventListener versus old-style property?

javascriptxmlhttprequest

提问by Delan Azabani

readystatechangeis a standard event for XMLHttpRequestobjects, and so should be able to have functions listen on the event either using

readystatechangeXMLHttpRequest对象的标准事件,因此应该能够让函数使用

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?

然而,后一种方法似乎只适用于 Firefox 和 Chrome,但不适用于 Opera,它不会抛出错误,但根本没有效果。为什么会这样,这甚至是正确的行为吗?

采纳答案by dtech

The MDN docs on XMLHttpRequestdon't specifically mention raising a readystatechangeevent, but the W3C docsdo require it.

XMLHttpRequest 上MDN 文档没有特别提到引发readystatechange事件,但W3C 文档确实需要它。

That combined with the general rule "onxxxis the event handler for event xxx" would imply that the Opera behaviour is incorrect.

结合一般规则“onxxx是事件的事件处理程序xxx”将意味着 Opera 行为是不正确的。

回答by jantje19

This worked for me.

这对我有用。

xhr.addEventListener('readystatechange', evt => {
    if (this.readyState == 4 && this.status == 200) {
        console.log(this.responseText);
        return this.responseText;
    }
}, false);