挂接到 XMLHttpRequest open and send 方法
Hook into XMLHttpRequest open and send method
我使用以下代码挂接到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"作为一个数组,并且您始终推送数据,而不是每次都覆盖它。
相关文章:
- Selenium WebDriver and JavaScript change
- PHP and Javascript functions
- Javascript Return and if/else
- SetTimeout and clearTimeout in Javascript
- lightbox in html 5 and javascript
- TimelineJS and AngularJS
- timeago.js with datatable and PHP
- javascript button ajax and php
- Ajax and Json with Rails
- Combine onload, onresize and onclick
- php布尔值's小写AND大写和数字布尔值'可以接受
- setTimeout and V8
- Jquery post and onclick
- 来自现场目的的Meteor电子邮件.send()
- Moment js and IOS
- XMLHttpRequest Open and Send:如何判断它是否有效
- 挂接到 XMLHttpRequest open and send 方法
- Socket and node.js send
- jquery ajax send form.serialize, variable and array all as d
- res.send and res.render calls