首頁  >  文章  >  web前端  >  透過JS 攔截全域ajax請求實例解析

透過JS 攔截全域ajax請求實例解析

高洛峰
高洛峰原創
2017-03-28 14:39:002456瀏覽

你是否有過下面的需求:需要給所有ajax請求添加統一簽名、需要統計某個接口被請求的次數、需要限制http請求的方法必須為get或post、需要分析別人網絡協議等等,那麼如何做?想想,如果能夠攔截所有ajax請求,那麼問題就會變的很簡單!

Ajax-hook源碼位址: https://github.com/wendux/Ajax-hook 

如何使用

1.引入ajaxhook. 。

<script src="wendu.ajaxhook.js"></script>

ok, 我們使用jQuery(v3.1) 的get方法來測一下:

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])
}
})
結果 :

// get current page source code 
$.get().done(function(d){
console.log(d.substr(0,30)+"...")
})

攔截成功了! 我們也可以看到jQuery3.1內部已經放棄onreadystatechange而改用onload了。

API


hookAjax(ob)

1.ob,類型是對象,key為想要攔截的回呼或函數,value為我們的攔截函數。 2.傳回值: 原始的 XMLHttpRequest。如果有寫請求不想被攔截,可以new 這個。

unHookAjax()

1.載攔截;卸載後,攔截將失效。 改變ajax行為

攔截所有ajax請求,檢測請求method,如果是“GET”,則中斷請求並給出提示

> open called: method:GET,url:http://localhost:63342/Ajax-hook/demo.html,async:true
> onload called: XMLHttpRequest
> <!DOCTYPE html>
<html>
<head l...

攔截所有ajax請求,請求統一添加時間戳

hookAjax({
open:function(arg){
if(arg[0]=="GET"){
console.log("Request was aborted! method must be post! ")
return true;
}
} 
})

修改請求返回的數據「responseText」

hookAjax({
open:function(arg){
arg[1]+="?timestamp="+Date.now();
} 
})

結果:

hookAjax({
onload:function(xhr){
//请求到的数据首部添加"hook!" 
xhr.responseText="hook!"+xhr.responseText;
}
})

 有了這些範例,相信開頭提到的需求都很容易實現。最後測一下unHook

hook!<!DOCTYPE html>
<html>
<h...

輸出:

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))
})
})

注意

1.攔截函數回傳值是一個boolean,如果為true則會阻斷ajax請求,默認為false,不會阻斷請求。

2.所有的回調攔截函數的參數為當前的XMLHttpRequest 實例,如onreadystatechange、onload;所有ajax原始方法的攔截函數會將原始參數以數組的形式傳遞給攔截函數,你可以在攔截函數中修改它。


以上所述是小編給大家介紹的JS 攔截全局ajax請求實例解析,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回覆大家的。


相關文章:

解決攔截器對ajax請求的攔截實例詳解

Node.js伺服器環境下使用Mock.js攔截AJAX請求的教學

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn