钩入XMLHttpRequest打开并发送方法

时间:2012-05-07 08:52:08

标签: javascript ajax

我使用以下代码挂钩到XMLHttpRequest打开/发送方法:

var lastParams = '';
var send = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function(data){
   lastParams = data;
   send.call(this, data);
};

var open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(method, uri, async, user, pass) {
    this.addEventListener("readystatechange", function(event) {  
    if(this.readyState == 4){
       var self = this;
       var response = {
         method: method,
         uri: uri,
         params: lastParams,
         responseText: self.responseText
      };
      console.log(response);  
    }
  }, false);
  open.call(this, method, uri, async, user, pass);
};

在一次单个ajax请求的情况下工作正常。

当一次触发多个ajax请求时,lastParams可能包含错误的数据(意味着lastParams可以包含来自其他ajax请求的数据)。我想唯一地将lastParams与请求的其他属性相关联吗?

XMLHttpRequest中是否有任何id属性,以便我可以唯一标识ajax请求实例?

提前致谢。

3 个答案:

答案 0 :(得分:1)

为了将某些数据与指定的XMLHttpRequest实例唯一关联,您只需将属性添加到XMLHttpRequest实例中,并将数据保存到属性中。例如:

// generating data for request
var data=generateData();

// sending data
var xhr=new XMLHttpRequest();
xhr.open("POST","/yourpage.php",true);
xhr.onreadystatechange=function(event){
  if(this.readyState===4){
    console.log(this.mySendedData);
  }
};
/** if you need to preserve 'data' variable value for each xhr **/
xhr.mySendedData=data;
/***************************************************************/
xhr.send(data);

答案 1 :(得分:1)

查看https://github.com/jpillora/xhookdemos

//modify 'responseText' of 'example2.txt'
xhook.after(function(request, response) {
  if(request.url.match(/example\.txt$/)) {
    response.text = response.text.replace(/[aeiou]/g,'z');
  }
});

答案 2 :(得分:0)

为什么不制作' lastParams'作为一个数组,你总是推送数据,而不是每次都覆盖它。