gpt4 book ai didi

javascript - 如何重写 XMLHttpRequest?

转载 作者:行者123 更新时间:2023-11-27 22:58:41 25 4
gpt4 key购买 nike

我想重写“XMLHttpRequest”这个构造函数。

我只想在新建实例时发出警报,就像这样:(这不是我真正想做的,只是一个例子)

var ajax_request = new XMLHttpRequest(); //then alert "new a XMLHttpRequest instance!"

然后我试试这个:

var orig_XMLHttpRequest = window.XMLHttpRequest;
window.XMLHttpRequest = function() {
alert("new a XMLHttpRequest instance!");
orig_XMLHttpRequest.apply(this, arguments);
};

但是当我新建一个实例时,

我在 orig_XMLHttpRequest.apply(this, argument); 处收到此错误

TypeError: Constructor XMLHttpRequest requires 'new'

那么,我哪一步做错了?如何覆盖 XMLHttpRequest?还是不可能?

我也尝试这个:

var orig_XMLHttpRequest = window.XMLHttpRequest;
window.XMLHttpRequest = function() {
alert("new a XMLHttpRequest instance!");
new (Function.prototype.bind.apply(orig_XMLHttpRequest, arguments));
};

var ajax_request = new XMLHttpRequest();
ajax_request.open("POST", "./php/register.php", true);
ajax_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax_request.onreadystatechange = function() {.....};
ajax_request.send();

但我仍然遇到错误:(

TypeError: ajax_request.open is not a function

最佳答案

有趣的问题。

我已经能够修改您的第二个代码示例以使其正常工作:

var orig_XMLHttpRequest = window.XMLHttpRequest;
window.XMLHttpRequest = function() {
document.write("new a XMLHttpRequest instance!");
return new orig_XMLHttpRequest();
};

var ajax_request = new XMLHttpRequest();
ajax_request.open("POST", "./php/register.php", true);
ajax_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax_request.onreadystatechange = function() {
if (ajax_request.readyState === XMLHttpRequest.DONE) {
console.log("request returned status code: " + ajax_request.status);
}
}
ajax_request.onerror = function(e) {
console.log("request failed: " + e.target.status);
}

ajax_request.send();

关于javascript - 如何重写 XMLHttpRequest?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37340816/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com