在新项目中,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被成功拦截了,效果不错。
总结
到此这篇关于jquery项目中如何防重复提交的文章就介绍到这了,更多相关jquery防重复提交内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!