挂接到 XMLHttpRequest open and send 方法

Hook into XMLHttpRequest open and send method

本文关键字:and send 方法 open XMLHttpRequest      更新时间:2023-09-26

我使用以下代码挂接到XMLHttpRequest open/send 方法:

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 请求实例?

提前谢谢。

看看 https://github.com/jpillora/xhook 和演示

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

为了唯一地将某些数据与指定的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);

为什么不将"lastParams"作为一个数组,并且您始终推送数据,而不是每次都覆盖它。