通过JS拦截全局ajax请求实例解析
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了通过JS拦截全局ajax请求实例解析,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含3056字,纯文字阅读大概需要5分钟。
内容图文
![通过JS拦截全局ajax请求实例解析](/upload/InfoBanner/zyjiaocheng/304/2930361369084bcd87941ded09a8d4f4.jpg)
Ajax-hook源码地址 : https://github.com/wendux/Ajax-hook
如何使用
1.引入ajaxhook.js
<script src="wendu.ajaxhook.js"></script>
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 > <!DOCTYPE html> <html> <head l...
拦截成功了! 我们也可以看到jQuery3.1内部已经放弃onreadystatechange而改用onload了。
API
hookAjax(ob)
1.ob,类型是对象,key为想要拦截的回调或函数,value为我们的拦截函数。
2.返回值: 原始的 XMLHttpRequest。如果有写请求不想被拦截,可以new 这个。
unHookAjax()
1.载拦截;卸载后,拦截将失效。
改变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!<!DOCTYPE html> <html> <h...
有了这些示例,相信开篇提到的需求都很容易实现。最后测一下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<!DOCTYPE html> <html> <he... unhook <!DOCTYPE
注意
1.拦截函数返回值是一个boolean,如果为true则会阻断ajax请求,默认为false,不会阻断请求。
2.所有的回调拦截函数的参数为当前的XMLHttpRequest 实例,如onreadystatechange、onload;所有ajax原始方法的拦截函数会将原始参数以数组的形式传递给拦截函数,你可以在拦截函数中修改它。
以上所述是小编给大家介绍的JS 拦截全局ajax请求实例解析,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。
相关文章:
解决拦截器对ajax请求的拦截实例详解
Node.js服务器环境下使用Mock.js拦截AJAX请求的教程
通过php检查是否是ajax请求的方法
内容总结
以上是互联网集市为您收集整理的通过JS拦截全局ajax请求实例解析全部内容,希望文章能够帮你解决通过JS拦截全局ajax请求实例解析所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。