在新專案中,axios能實作防重復提交的功能,不過老專案(例如jQuery)的專案中,沒有axios,但是匯入Ajax-hook
就可以實作
Ajax-hook原始碼地址 : https://github.com/wendux/Ajax-hook
匯入
<script src="https://unpkg.com/ajax-hook@2.0.3/dist/ajaxhook.min.js"></script>
ah物件是在匯入ajaxhook.min.js后就會出現的,使用:
ah.proxy({
//請求發起前進入
onRequest: (config, handler) => {
console.log(config.url)
handler.next(config);
},
//請求發生錯誤時進入,比如超時;注意,不包括http狀態碼錯誤,如404仍然會認為請求成功
onError: (err, handler) => {
console.log(err.type)
handler.next(err)
},
//請求成功后進入
onResponse: (response, handler) => {
console.log(response.response)
handler.next(response)
}
})
其中,config.method為ajax請求的方式(GET/POST),config.url為請求的路徑,onError中的err物件和onResponse中的response可以通過err.config.method/response.config.method來獲得ajax的請求方式,
我稍微封裝了一下,實作防重復提交的js檔案,親測有效,朋友們可以后再測驗一下,歡迎各路大神談論和指出不足,
```javascript
function laodJS(url, callback) {
var script = document.createElement('script');
fn = callback || function() {};
script.type = 'text/javascript';
script.defer = true;
// IE
if (script.readyState) {
script.onreadystatechange = function() {
if (script.readyState == 'loaded' || script.readyState == 'complete') {
script.onreadystatechange = null;
fn();
}
}
} else {
// 其他瀏覽器
script.onload = function() {
fn();
}
}
script.src = url;
document.getElementsByTagName('body')[0].appendChild(script);
}
laodJS('https://unpkg.com/ajax-hook@2.0.3/dist/ajaxhook.min.js', function() {
let ajaxArr = []
ah.proxy({
//請求發起前進入
onRequest: (config, handler) => {
var id = config.method + config.url
if (ajaxArr.indexOf(id) === -1) {
// 給每個請求設定唯一ID,push到ajaxArr里,在請求完成時再移除那個項
ajaxArr.push(id)
handler.next(config);
} else {
return handler.reject()
}
},
//請求發生錯誤時進入,比如超時;注意,不包括http狀態碼錯誤,如404仍然會認為請求成功
onError: (err, handler) => {
var id = err.config.method + err.config.url
if (ajaxArr.indexOf(id) !== -1) {
ajaxArr.splice(ajaxArr.indexOf(id), 1)
}
handler.next(err)
},
//請求成功后進入
onResponse: (response, handler) => {
var id = response.config.method + response.config.url
if (ajaxArr.indexOf(id) !== -1) {
ajaxArr.splice(ajaxArr.indexOf(id), 1)
}
handler.next(response)
}
})
})
直接在全域中引入這個檔案就可以了,我這個檔案命名為preventRepeatSubmission.js,
我的HTML代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h1>This is index Page</h1>
<ul>
<li><a href="/">/</a></li>
<li><a href="/index">index頁面</a></li>
<li><a href="/404">404頁面</a></li>
<li><a href="/info">info頁面</a></li>
<li><a href="/nofound">nofound</a></li>
</ul>
<button id="sendMsg">請求攔截器</button>
<script src="./jquery.min.js"></script>
<!-- <script src="https://unpkg.com/ajax-hook@2.0.3/dist/ajaxhook.min.js"></script> -->
<script src="./preventRepeatSubmission.js"></script>
<script>
document.getElementById("sendMsg").addEventListener("click", function() {
$.ajax({
url: 'http://localhost:3000/home',
type: 'GET',
success: function(data) {
console.log('success', data)
}
})
})
</script>
</body>
</html>
我的服務器使用koa2搭建的,代碼如下:
const Koa = require('koa');
const Router = require('koa-router');
const app = new Koa();
const router = new Router();
router
.get('/', (ctx, next) => {
ctx.body = '<h1>hello jspang</h1>';
})
.get('/home', async (ctx, next) => {
// ctx.body = '<h1>This is home Page</h1>'
async function delay(time) {
return new Promise(function(resolve, reject) {
setTimeout(function(){
resolve();
}, time);
});
};
await delay(5000);
const url = ctx.url;
// 在request中獲取get請求引數
const request = ctx.request;
const request_query = request.query;
const request_querystring = request.querystring;
// 在ctx中獲取get請求的引數
const ctx_query = ctx.query;
const ctx_querystring = ctx.querystring;
ctx.body = {url, request_query, request_querystring, ctx_query, ctx_querystring};
ctx.response.body = {status:200, msg:'已經成功獲得引數'};
})
app
.use(router.routes()) // 向app中裝載路由
.use(router.allowedMethods()) // 裝載中間件
app.listen(3000, () => {
console.log('[Demo] is running at port 3000');
});
瀏覽器測驗效果:

按下圖中的button就會發起一次ajax請求,我的服務器是延遲回應5s的,在這延遲5s期間,我有點擊了20次button,發起相同的20次ajax被成功攔截了,效果不錯,請看官留下你的的小贊贊吧,如果錯誤歡迎給位大神指出,一起學習,謝謝,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/352248.html
標籤:其他
