javascript - 为收到的每个数据获取 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)
我想知道我做错了什么以及如何让它发挥作用。谢谢!
解决方案
您分配给实例化对象prototype
的属性,而不是. 您可能想要更改:XMLHttpRequest
XMLHttpRequest.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
是不好的做法 - 如果可能,请考虑避免它)
推荐阅读
- git - git-secret 揭示导致 pubring.kbx 文件的更改 - 为什么?
- python - Python:从二维列表中删除较低版本
- javascript - onChange 的反应没有像我预期的那样工作
- json - 通过 httpentity 将请求正文作为 json 发送到 GET 请求
- javascript - 在刷新时保持可折叠行的状态
- python - 抓取时出现 UnboundLocalError
- json - 在 kotlinx.serialization 中反序列化二维数组
- entity-relationship - ER图帮助,
- javascript - Node.js - 原生 HTTP 如何删除 cookie
- amazon-quicksight - AWS Quicksight - 如何按总和然后平均分组?