开发者

Change function on javascript prototype

I want to change the XMLHttpRequest send function so that a function is called before the request is made and after the request is complete. Here is what I have so far:

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";
    ajax开发者_Python百科Count--;
    document.getElementById("buttonClicky").innerHTML = "Count: " + ajaxCount;
}

However, I'm doing something wrong here because once it hits the oldSend() call, it never returns or triggers the onreadystatechange event. So I must be doing somethingclickCount wrong here. Any ideas? I set a breakpoint and it gets hit just fine when I call this:

$.ajax({
    type: "GET",
    url: "file.txt",
    success: function(result) {
                    //this never gets called
        document.getElementById("myDiv").innerHTML = result;
    }
});

So my new function is getting called. I guess just don't know how to call the old function. Any ideas on how to fix this code so that the Ajax Request is actually made and my new callback gets called?

Note: I'm aware of the JQuery events that essentially do this. But I'm doing this so I can get it to work with any Ajax call (Mootools, GWT, etc). I am just happening to test it with Jquery.


You need to call old functions in the context of this.

E.g.: oldSend.call(this)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜