你是否有過(guò)下面的需求:需要給所有ajax請(qǐng)求添加統(tǒng)一簽名、需要統(tǒng)計(jì)某個(gè)接口被請(qǐng)求的次數(shù)、需要限制http請(qǐng)求的方法必須為get或post、需要分析別人網(wǎng)絡(luò)協(xié)議等等,那么如何做?想想,如果能夠攔截所有ajax請(qǐng)求,那么問(wèn)題就會(huì)變的很簡(jiǎn)單!😄,少年,想法有點(diǎn)大膽,不過(guò),我欣賞!直接上輪子,Ajax-hook不僅可以滿(mǎn)足你想要的,同時(shí)可以給你更多。
Ajax-hook源碼地址 : https://github.com/wendux/Ajax-hook
如何使用
1.引入ajaxhook.js
<script src="wendu.ajaxhook.js"></script>
2.攔截需要的ajax 回調(diào)或函數(shù)。
hookAjax({//攔截回調(diào)onreadystatechange:function(xhr){console.log("onreadystatechange called: %O",xhr)},onload:function(xhr){console.log("onload called: %O",xhr)},//攔截函數(shù)open:function(arg){console.log("open called: method:%s,url:%s,async:%s",arg[0],arg[1],arg[2])}})
ok, 我們使用jQuery(v3.1) 的get方法來(lái)測(cè)一下:
// get current page source code $.get().done(function(d){console.log(d.substr(0,30)+"...")})
結(jié)果 :
> open called: method:GET,url:http://localhost:63342/Ajax-hook/demo.html,async:true> onload called: XMLHttpRequest> <!DOCTYPE html><html><head l...
攔截成功了! 我們也可以看到j(luò)Query3.1內(nèi)部已經(jīng)放棄onreadystatechange而改用onload了。
API
hookAjax(ob)
unHookAjax()
改變ajax行為
攔截所有ajax請(qǐng)求,檢測(cè)請(qǐng)求method,如果是“GET”,則中斷請(qǐng)求并給出提示
hookAjax({open:function(arg){if(arg[0]=="GET"){console.log("Request was aborted! method must be post! ")return true;}} })
攔截所有ajax請(qǐng)求,請(qǐng)求統(tǒng)一添加時(shí)間戳
hookAjax({open:function(arg){arg[1]+="?timestamp="+Date.now();} })
修改請(qǐng)求返回的數(shù)據(jù)“responseText”
hookAjax({onload:function(xhr){//請(qǐng)求到的數(shù)據(jù)首部添加"hook!" xhr.responseText="hook!"+xhr.responseText;}})
結(jié)果:
hook!<!DOCTYPE html><html><h...
有了這些示例,相信開(kāi)篇提到的需求都很容易實(shí)現(xiàn)。最后測(cè)一下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 XMLHttpRequestconsole.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:truesend called: nullonload calledhook<!DOCTYPE html><html><he...unhook<!DOCTYPE
注意
1.攔截函數(shù)返回值是一個(gè)boolean,如果為true則會(huì)阻斷ajax請(qǐng)求,默認(rèn)為false,不會(huì)阻斷請(qǐng)求。
2.所有的回調(diào)攔截函數(shù)的參數(shù)為當(dāng)前的XMLHttpRequest 實(shí)例,如onreadystatechange、onload;所有ajax原始方法的攔截函數(shù)會(huì)將原始參數(shù)以數(shù)組的形式傳遞給攔截函數(shù),你可以在攔截函數(shù)中修改它。
以上所述是小編給大家介紹的JS 攔截全局ajax請(qǐng)求實(shí)例解析,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)武林網(wǎng)網(wǎng)站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注