Javascript更改XMLHttpRequest onreadystatechange回调

时间:2014-10-13 23:11:00

标签: javascript ajax hook

我尝试更改onreadystatechange回调。我的Javascript看起来像这样

(function() {
    var open_original = XMLHttpRequest.prototype.open;
    var send_original = XMLHttpRequest.prototype.send;

    XMLHttpRequest.prototype.open = function(method, url, async, unk1, unk2) {
        // console.log(url);
        open_original.apply(this, arguments);
    };

    XMLHttpRequest.prototype.send = function(data) {
        this.onreadystatechange = function() {
            console.log('asdasdh adzl8 ada');
        }
        send_original.apply(this, arguments);
    };
})();

永远不会调用匿名函数。为什么呢?

1 个答案:

答案 0 :(得分:3)

这似乎对我很好:

(function() {
    var open_original = XMLHttpRequest.prototype.open;
    var send_original = XMLHttpRequest.prototype.send;

    XMLHttpRequest.prototype.open = function(method, url, async, unk1, unk2) {
        open_original.apply(this, arguments);
    };

    XMLHttpRequest.prototype.send = function(data) {
        this.onreadystatechange = function() {
            console.log('Works for me.');
        }
        send_original.apply(this, arguments);
    };
})();
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', '/echo/html/', true);
xmlhttp.send();

http://jsfiddle.net/ers2s80a/

Screen shot