为页面上的所有AJAX请求添加“钩子”我想知道是否可以“挂钩”每个AJAX请求(无论是要发送还是事件)并执行操作。此时我假设页面上还有其他第三方脚本。其中一些可能使用jQuery,而另一些则不然。这可能吗?
3 回答
精慕HU
TA贡献1845条经验 获得超8个赞
受到aviv的回答的启发,我做了一些调查,这就是我想出来的。根据脚本中的注释,
我不确定它是否有用,当然只适用于使用本机XMLHttpRequest对象的浏览器。
我认为如果javascript库正在使用它将会起作用,因为如果可能的话它们将使用本机对象。
function addXMLRequestCallback(callback){
var oldSend, i;
if( XMLHttpRequest.callbacks ) {
// we've already overridden send() so just add the callback
XMLHttpRequest.callbacks.push( callback );
} else {
// create a callback queue
XMLHttpRequest.callbacks = [callback];
// store the native send()
oldSend = XMLHttpRequest.prototype.send;
// override the native send()
XMLHttpRequest.prototype.send = function(){
// process the callback queue
// the xhr instance is passed into each callback but seems pretty useless
// you can't tell what its destination is or call abort() without an error
// so only really good for logging that a request has happened
// I could be wrong, I hope so...
// EDIT: I suppose you could override the onreadystatechange handler though
for( i = 0; i < XMLHttpRequest.callbacks.length; i++ ) {
XMLHttpRequest.callbacks[i]( this );
}
// call the native send()
oldSend.apply(this, arguments);
}
}}// e.g.addXMLRequestCallback( function( xhr ) {
console.log( xhr.responseText ); // (an empty string)});addXMLRequestCallback( function( xhr ) {
console.dir( xhr ); // have a look if there is anything useful here});
猛跑小猪
TA贡献1858条经验 获得超8个赞
既然你提到的jQuery,我知道jQuery提供了一个.ajaxSetup()用于设置全局AJAX选项,其中包括事件触发类似方法success,error和beforeSend-这是什么听起来像你在找什么。
$.ajaxSetup({
beforeSend: function() {
//do stuff before request fires
}});当然,您需要在尝试使用此解决方案的任何页面上验证jQuery可用性。
添加回答
举报
0/150
提交
取消
