js请求结果拦截机器_JS 拦截全局ajax请求实例解析

你是否有过下面的需求:需要给所有ajax请求添加统一签名、需要统计某个接口被请求的次数、需要限制http请求的方法必须为get或post、需要分析别人网络协议等等,那么如何做?想想,如果能够拦截所有ajax请求,那么问题就会变的很简单!😄,少年,想法有点大胆,不过,我欣赏!直接上轮子,Ajax-hook不仅可以满足你想要的,同时可以给你更多。

如何使用

1.引入ajaxhook.js

2.拦截需要的ajax 回调或函数。

hookAjax({

//拦截回调

onreadystatechange:function(xhr){

console.log("onreadystatechange called: %O",xhr)

},

onload:function(xhr){

console.log("onload called: %O",xhr)

},

//拦截函数

open:function(arg){

console.log("open called: method:%s,url:%s,async:%s",arg[0],arg[1],arg[2])

}

})

ok, 我们使用jQuery(v3.1) 的get方法来测一下:

// get current page source code

$.get().done(function(d){

console.log(d.substr(0,30)+"...")

})

结果 :

> open called: method:GET,url:http://localhost:63342/Ajax-hook/demo.html,async:true

> onload called: XMLHttpRequest

>

拦截成功了! 我们也可以看到jQuery3.1内部已经放弃onreadystatechange而改用onload了。

API

hookAjax(ob)

ob,类型是对象,key为想要拦截的回调或函数,value为我们的拦截函数。

返回值: 原始的 XMLHttpRequest。如果有写请求不想被拦截,可以new 这个。

unHookAjax()

卸载拦截;卸载后,拦截将失效。

改变ajax行为

拦截所有ajax请求,检测请求method,如果是“GET”,则中断请求并给出提示

hookAjax({

open:function(arg){

if(arg[0]=="GET"){

console.log("Request was aborted! method must be post! ")

return true;

}

}

})

拦截所有ajax请求,请求统一添加时间戳

hookAjax({

open:function(arg){

arg[1]+="?timestamp="+Date.now();

}

})

修改请求返回的数据“responseText”

hookAjax({

onload:function(xhr){

//请求到的数据首部添加"hook!"

xhr.responseText="hook!"+xhr.responseText;

}

})

结果:

hook!

有了这些示例,相信开篇提到的需求都很容易实现。最后测一下unHook

hookAjax({

onreadystatechange:function(xhr){

console.log("onreadystatechange called: %O",xhr)

//return true

},

onload:function(xhr){

console.log("onload called")

xhr.responseText="hook"+xhr.responseText;

//return true;

},

open:function(arg){

console.log("open called: method:%s,url:%s,async:%s",arg[0],arg[1],arg[2])

arg[1]+="?hook_tag=1";

},

send:function(arg){

console.log("send called: %O",arg[0])

}

})

$.get().done(function(d){

console.log(d.substr(0,30)+"...")

//use original XMLHttpRequest

console.log("unhook")

unHookAjax()

$.get().done(function(d){

console.log(d.substr(0,10))

})

})

输出:

open called: method:GET,url:http://localhost:63342/Ajax-hook/demo.html,async:true

send called: null

onload called

hook

unhook

/p>

注意

1.拦截函数返回值是一个boolean,如果为true则会阻断ajax请求,默认为false,不会阻断请求。

2.所有的回调拦截函数的参数为当前的XMLHttpRequest 实例,如onreadystatechange、onload;所有ajax原始方法的拦截函数会将原始参数以数组的形式传递给拦截函数,你可以在拦截函数中修改它。

以上所述是小编给大家介绍的JS 拦截全局ajax请求实例解析,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值