首页 > 解决方案 > 为收到的每个数据获取 XMLHttpRequest 响应

问题描述

我正在尝试制作一个脚本,该脚本将在当前页面上收到数据时返回响应。(收到新数据 > 将其内容记录到控制台)

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == XMLHttpRequest.DONE) {
        console.log(xhr.responseText);
    }
}
xhr.prototype.open = (function(fopen){
    return function(){
        console.log("Data received.");
        return fopen.apply(this,arguments); 
    }
})(XMLHttpRequest.prototype.open);

上面的脚本就是这个脚本。(来源

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == XMLHttpRequest.DONE) {
        console.log(xhr.responseText);
    }
}
xhr.open('GET', 'http://example.com', true);
xhr.send(null);

结合这个脚本。(来源

XMLHttpRequest.prototype.open = (function(fopen){
return function(){
    console.log("Data received.");
    return fopen.apply(this,arguments); 
}
})(XMLHttpRequest.prototype.open)

我想知道我做错了什么以及如何让它发挥作用。谢谢!

标签: javascriptxmlhttprequest

解决方案


您分配给实例化对象prototype的属性,而不是. 您可能想要更改:XMLHttpRequestXMLHttpRequest.prototype.onreadystatechange

Object.defineProperty(XMLHttpRequest.prototype, 'onreadystatechange', {
  set: function(listenerFn) {
    this.addEventListener('readystatechange', function(...handlerArgs) {
      if (this.readyState == XMLHttpRequest.DONE) {
        // Custom action:
        // console.log(xhr.responseText);
        console.log('Detected a new response');
        // Run the previous callback that was passed in:
        listenerFn.apply(this, handlerArgs);
      }
    });
  }
});

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://stacksnippets.net');
xhr.onreadystatechange = () => console.log('handler running');
xhr.send();

当然,这并不完全符合规范,这只是一个可能开始的猴子补丁示例。(但是,像这样改变内置对象XMLHttpRequest.prototype是不好的做法 - 如果可能,请考虑避免它)


推荐阅读