欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript中如何校驗接口是否重復(fù)提交

 更新時間:2024年03月21日 09:57:41   作者:長相思979  
這篇文章主要為大家詳細介紹了在JavaScript中如何校驗接口是否重復(fù)提交,文中的示例代碼講解詳細,有需要的小伙伴可以跟隨小編一起學(xué)習(xí)一下

JS校驗接口重復(fù)提交

示例代碼

request.js

import axios from 'axios'
import { Notification, MessageBox, Message, Loading } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import { tansParams, blobValidate } from "@/utils/ruoyi";
import cache from '@/plugins/cache'
import { saveAs } from 'file-saver'
 
let downloadLoadingInstance;
// 是否顯示重新登錄
export let isRelogin = { show: false };
 
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 創(chuàng)建axios實例
const service = axios.create({
  // axios中請求配置有baseURL選項,表示請求URL公共部分
  baseURL: process.env.VUE_APP_BASE_API,
  // 超時
  timeout: 10000
})
 
//     請求攔截器
service.interceptors.request.use(config => {
  // 是否需要設(shè)置 token
  const isToken = (config.headers || {}).isToken === false
  // 是否需要防止數(shù)據(jù)重復(fù)提交
  const isRepeatSubmit = (config.headers || {}).repeatSubmit === false
  if (getToken() && !isToken) {
    config.headers['Authorization'] = 'Bearer ' + getToken() // 讓每個請求攜帶自定義token 請根據(jù)實際情況自行修改
  }
  // get請求映射params參數(shù)
  if (config.method === 'get' && config.params) {
    let url = config.url + '?' + tansParams(config.params);
    url = url.slice(0, -1);
    config.params = {};
    config.url = url;
  }
  if (!isRepeatSubmit && (config.method === 'post' || config.method === 'put')) {
    const requestObj = {
      url: config.url,
      data: typeof config.data === 'object' ? JSON.stringify(config.data) : config.data,
      time: new Date().getTime()
    }
    const requestSize = Object.keys(JSON.stringify(requestObj)).length; // 請求數(shù)據(jù)大小
    const limitSize = 5 * 1024 * 1024; // 限制存放數(shù)據(jù)5M
    if (requestSize >= limitSize) {
      console.warn(`[${config.url}]: ` + '請求數(shù)據(jù)大小超出允許的5M限制,無法進行防重復(fù)提交驗證。')
      return config;
    }
    const sessionObj = cache.session.getJSON('sessionObj')
    if (sessionObj === undefined || sessionObj === null || sessionObj === '') {
      cache.session.setJSON('sessionObj', requestObj)
    } else {
      const s_url = sessionObj.url;                  // 請求地址
      const s_data = sessionObj.data;                // 請求數(shù)據(jù)
      const s_time = sessionObj.time;                // 請求時間
      const interval = 1000;                         // 間隔時間(ms),小于此時間視為重復(fù)提交
      //此處校驗是否是重復(fù)提交
      if (s_data === requestObj.data && requestObj.time - s_time < interval && s_url === requestObj.url) {
        const message = '數(shù)據(jù)正在處理,請勿重復(fù)提交';
        console.warn(`[${s_url}]: ` + message)
        return Promise.reject(new Error(message))
      } else {
        cache.session.setJSON('sessionObj', requestObj)
      }
    }
  }
  return config
}, error => {
    console.log(error)
    Promise.reject(error)
})
 
// 響應(yīng)攔截器
service.interceptors.response.use(res => {
    // 未設(shè)置狀態(tài)碼則默認成功狀態(tài)
    const code = res.data.code || 200;
    // 獲取錯誤信息
    const msg = errorCode[code] || res.data.msg || errorCode['default']
    // 二進制數(shù)據(jù)則直接返回
    if (res.request.responseType ===  'blob' || res.request.responseType ===  'arraybuffer') {
      return res.data
    }
    if (code === 401) {
      if (!isRelogin.show) {
        isRelogin.show = true;
      //   MessageBox.confirm('登錄狀態(tài)已過期,您可以繼續(xù)留在該頁面,或者重新登錄', '系統(tǒng)提示', { confirmButtonText: '重新登錄', cancelButtonText: '取消', type: 'warning' }).then(() => {
      //     isRelogin.show = false;
      //     store.dispatch('LogOut').then(() => {
      //       location.href = '/index';
      //     })
      // }).catch(() => {
      //   isRelogin.show = false;
      // });
    }
      return Promise.reject('無效的會話,或者會話已過期,請重新登錄。')
    } else if (code === 500) {
      Message({ message: msg, type: 'error' })
      return Promise.reject(new Error(msg))
    } else if (code === 601) {
      Message({ message: msg, type: 'warning' })
      return Promise.reject('error')
    } else if (code === 1) {
      return res.data
    } else if(res.code !== 200){
      Notification.error({ title: msg })
      return Promise.reject('error')
    } else{
      return res.data
    }
  },
  error => {
    console.log('err' + error)
    let { message } = error;
    if (message == "Network Error") {
      message = "后端接口連接異常";
    } else if (message.includes("timeout")) {
      message = "系統(tǒng)接口請求超時";
    } else if (message.includes("Request failed with status code")) {
      message = "系統(tǒng)接口" + message.substr(message.length - 3) + "異常";
    }
    Message({ message: message, type: 'error', duration: 5 * 1000 })
    return Promise.reject(error)
  }
)
 
// 通用下載方法
export function download(url, params, filename, config) {
  downloadLoadingInstance = Loading.service({ text: "正在下載數(shù)據(jù),請稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
  return service.post(url, params, {
    transformRequest: [(params) => { return tansParams(params) }],
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    responseType: 'blob',
    ...config
  }).then(async (data) => {
    const isBlob = blobValidate(data);
    if (isBlob) {
      const blob = new Blob([data])
      saveAs(blob, filename)
    } else {
      const resText = await data.text();
      const rspObj = JSON.parse(resText);
      const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
      Message.error(errMsg);
    }
    downloadLoadingInstance.close();
  }).catch((r) => {
    console.error(r)
    Message.error('下載文件出現(xiàn)錯誤,請聯(lián)系管理員!')
    downloadLoadingInstance.close();
  })
}
 
export default service

方法補充

除了上文的方法,小編還為大家整理了一些其他JavaScript接口防重復(fù)提交的方法,希望對大家有所幫助

方法一:js防止重復(fù)提交接口

思路:定義一個事件的標識變量為false,點擊事件里先判斷變量是否為true,是的話就不執(zhí)行,否者的話把變量改為true,之后再執(zhí)行點擊事件內(nèi)容即可。

下方代碼表示只執(zhí)行一次

let isFlag= false;
//點擊事件
$(document).on("click","#_submit",function (){
    if (isFlag) {
        return false;
    }
    isFlag= true;
    
    //執(zhí)行內(nèi)容。。。。。
})

方法二:防止重復(fù)點擊

定義一個clickThrottle.js文件

/* 防止重復(fù)點擊 */
let clickTimer = 0

function clickThrottle(interval = 3000) {
    let now = +new Date(); // 獲取當(dāng)前時間的時間戳
    let timer = clickTimer; // 記錄觸發(fā)事件的事件戳
	
    if (now - timer < interval) {
    	// 如果當(dāng)前時間 - 觸發(fā)事件時的事件 < interVal,那么不符合條件,直接return false,
    	// 不讓當(dāng)前事件繼續(xù)執(zhí)行下去
        return false;
    } else { 
    	// 反之,記錄符合條件觸發(fā)了事件的時間戳,并 return true,使事件繼續(xù)往下執(zhí)行
        clickTimer = now;
        return true;
    }
}

export default clickThrottle

+new Date()這個代碼是獲得當(dāng)前時間的時間戳,與 new Date().getTime() 、 new Date().valueOf() 以及 Date.now() 是一樣的。

方法三:兩種防止js重復(fù)執(zhí)行的方法

其一:

 function test(){
        console.log(0);
    }
    
    function throttle(fun){
        if(fun.timeoutId) {window.clearTimeout(fun.timeoutId);}
        fun.timeoutId = window.setTimeout(function(){
            fun();
           fun.timeoutId = null;
        }, 1000);
    }
    
    throttle(test);
    throttle(test);
    throttle(test);
    throttle(test);

其二:

//禁用按鈕
$('button').prop('disabled',true);
//回調(diào)函數(shù)啟用按鈕
$('button').prop('disabled',false);
如果想要最后一次點擊生效,把timer定時器放在函數(shù)外每次調(diào)用進行檢測;如果不涉及定時器,就在函數(shù)內(nèi)部把函數(shù)賦值給自己讓每次調(diào)用都執(zhí)行新的邏輯
 
var timer;
var foo = function() {
    timer && clearTimeout(timer);
    timer = setTimeout(function() {
        console.log(0);
    }, 5000);
    //something
}

到此這篇關(guān)于JavaScript中如何校驗接口是否重復(fù)提交的文章就介紹到這了,更多相關(guān)JavaScript接口重復(fù)提交內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 多次注冊事件會導(dǎo)致一個事件被觸發(fā)多次的解決方法

    多次注冊事件會導(dǎo)致一個事件被觸發(fā)多次的解決方法

    一個JavaScript邏輯,會自動綁定函數(shù)到按鈕的click事件,但是這段代碼會反復(fù)注冊事件,具體的解決方法如下,感興趣的朋友可以參考下
    2013-08-08
  • 關(guān)于ES6字符串的擴展詳解

    關(guān)于ES6字符串的擴展詳解

    es6這個String對象倒是擴展了不少方法,但是很多都是跟字符編碼相關(guān),下面這篇文章主要給大家介紹了關(guān)于ES6字符串?dāng)U展的相關(guān)資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下
    2022-08-08
  • 前端JS運算精度丟失的解決方法

    前端JS運算精度丟失的解決方法

    前端在處理小數(shù)或大整數(shù)時,由于 JavaScript 的 Number 類型使用 IEEE 754 雙精度浮點數(shù)表示,可能會出現(xiàn)精度丟失問題(如 0.1 + 0.2 = 0.30000000000000004),以下是常見的解決方案,需要的朋友可以參考下
    2025-03-03
  • ionic App問題總結(jié)系列之ionic點擊系統(tǒng)返回鍵退出App

    ionic App問題總結(jié)系列之ionic點擊系統(tǒng)返回鍵退出App

    本篇文章主要介紹了ionic App問題總結(jié)系列之ionic點擊系統(tǒng)返回鍵退出App,具有一定的參考價值,有興趣的可以了解一下
    2017-08-08
  • js利用cookie實現(xiàn)記住用戶頁面操作

    js利用cookie實現(xiàn)記住用戶頁面操作

    這篇文章主要給大家介紹了關(guān)于js利用cookie實現(xiàn)記住用戶頁面操作的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-03-03
  • 根據(jù)分辯率調(diào)用不同的CSS.

    根據(jù)分辯率調(diào)用不同的CSS.

    根據(jù)分辯率調(diào)用不同的CSS....
    2007-01-01
  • es5 類與es6中class的區(qū)別小結(jié)

    es5 類與es6中class的區(qū)別小結(jié)

    這篇文章主要給大家介紹了關(guān)于es5 類與es6中class區(qū)別的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-11-11
  • JavaScript indexOf()原理及使用方法詳解

    JavaScript indexOf()原理及使用方法詳解

    這篇文章主要介紹了JavaScript indexOf()原理及使用方法詳解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-07-07
  • 解決layui table表單提示數(shù)據(jù)接口請求異常的問題

    解決layui table表單提示數(shù)據(jù)接口請求異常的問題

    今天小編就為大家分享一篇解決layui table表單提示數(shù)據(jù)接口請求異常的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-09-09
  • js實現(xiàn)使用輸入input和改變change事件模擬手動輸入

    js實現(xiàn)使用輸入input和改變change事件模擬手動輸入

    聚焦于JavaScript中的輸入模擬技術(shù),本指南將帶你探索如何使用input和change事件來創(chuàng)造逼真的手動輸入效果,通過簡單的代碼實現(xiàn),你將掌握這一實用的技巧,為你的Web應(yīng)用增添交互的樂趣,需要的朋友可以參考下
    2024-03-03

最新評論