我想更改 XMLHttpRequest 发送函数,以便在发出请求之前和请求完成之后调用一个函数。这是我到目前为止所拥有的:
var oldSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function() {
//this never gets called
oldOnReady = this.onreadystatechange;
this.onreadystatechange = function() {
oldOnReady();
ajaxStopped();
}
ajaxStarted();
// according to http://www.w3.org/TR/XMLHttpRequest/
// there's only ever 0 or 1 parameters passed into this method
if(arguments && arguments.length > 0) {
oldSend(arguments[0]); //gets to here, calls this method, then nothing happens
} else {
oldSend();
}
}
function ajaxStarted() {
ajaxCount++;
document.getElementById("buttonClicky").innerHTML = "Count: " + ajaxCount;
}
function ajaxStopped() {
$("#isRunning")[0].innerHTML = "stopped";
ajaxCount--;
document.getElementById("buttonClicky").innerHTML = "Count: " + ajaxCount;
}
但是,我在这里做错了,因为一旦它命中 oldSend()
调用,它就永远不会返回或触发 onreadystatechange
事件。所以我一定是在这里做了一些错误的事情。有任何想法吗?我设置了一个断点,当我调用它时它会很好地命中:
$.ajax({
type: "GET",
url: "file.txt",
success: function(result) {
//this never gets called
document.getElementById("myDiv").innerHTML = result;
}
});
所以我的新函数被调用了。我想只是不知道如何调用旧函数。关于如何修复此代码以便实际发出 Ajax 请求并调用我的新回调有什么想法吗?
注意:我知道 JQuery 事件本质上是执行此操作的。但我这样做是为了让它能够与任何 Ajax 调用(Mootools、GWT 等)一起工作。我只是碰巧用 Jquery 测试它。
最佳答案
您需要在 this
上下文中调用旧
函数。
例如:oldSend.call(this)
关于javascript - 更改 JavaScript 原型(prototype)上的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4235998/