使用ajax在界面上做添加,在页面上的所有AJAX请求中添加一个“钩子”

此篇博客介绍了一个JavaScript函数,通过覆盖XMLHttpRequest的send方法,为所有使用原生对象发起的网络请求添加了回调。作者提供了两个示例,用于记录响应文本和检查请求对象详情,适用于那些不依赖库且需要监控网络请求的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

小编典典

受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

});

2020-07-26

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值