我想要在页面的所有ajax请求发出去之前和数据返回到页面上之前做一次拦截,
在发出去之前对请求参数做处理再发送,数据回来后对返回数据做处理再返回。
我用XMLHttpRequest谢了一段js代码做拦截,在发出去之前都没有问题,但是数据回来
后如果是异步的请求就拦截不到,比如用jQuery ajax发异步的请求,数据回来后就直接
进入success了,没有进入拦截器。简单的说就是onreadystatechange没有触发,请问
大家该怎么处理啊?纠结好久了,求帮助。谢谢。
以下是代码:
var open = window.XMLHttpRequest.prototype.open,
send = window.XMLHttpRequest.prototype.send,
onReadyStateChange;
function openReplacement(method, url, async, user, password) {
var syncMode = async !== false ? 'async' : 'sync';
return open.apply(this, arguments);//可以理解成是继承,继承open对象中的属性和方法
}
function sendReplacement(data) {
if(this.onreadystatechange) {
this._onreadystatechange = this.onreadystatechange;
}
this.onreadystatechange = onReadyStateChangeReplacement;
return send.apply(this, arguments);
}
function onReadyStateChangeReplacement() {
if(this.readyState==4) {
//做返回数据的处理
}
}
window.XMLHttpRequest.prototype.open = openReplacement;
window.XMLHttpRequest.prototype.send = sendReplacement;