防重复提交的几种方法

272 阅读1分钟
一、双重验证:定义一个参数请求前设置为false请求完成设置true,同时判断时间间隔,如果上次请求时间和本次请求时间小于2s判定为重复提交

    save(){
        let msg = this.data.msgValue;
        let currentTime = new Date();
        //防止两次点击操作间隔太快:发送事件连续触发时间短于2s,或连续两次发送内容相同,则返回
        if ((currentTime - this.data.lastSendTime < 2000) || (msg === this.data.msg)) {
            return;
        }
        if (msg && this.data.saveState) {
            this.data.saveState = false
            wx.request({
                url: 'http://localhost:8080',
                data: {
                    name:'豆豆',
                    age:19
                },
                header:{
                    "Content-Type": "application/json"
                },
                method: "POST",
                success:res=>{},
                fail:error=>{},
                complete:completeRes=>{
                    this.data.saveState = true
                    this.data.lastSendTime = currentTime
                }
            })
        }
    }
    

二、防抖节流 节流:在一定时间内连续触发某事件,在这段时间段内只执行首次触发的那一次。
module.exports = {
    // func 需要节流的函数  timeGap 时间
    throttleFunc: function throttleFunc(func, timeGap) {
        if (timeGap==null || typeof(timeGap)=="undefined") {
            timeGap = 2000 // 如果没有传递参数timeGap,或者该参数值为空,则使用默认值2000毫秒
        }
        let lastTime = null
        return function () {
            let currentTime = + new Date()
            if (currentTime - lastTime > timeGap || !lastTime) {
                func.apply(this, arguments)
                lastTime = currentTime
            }
        }
    },
}

使用:提交事件使用节流函数
    var utils = require("../utils/utils.js")
    save: utils.throttleFunc(function(e) {
        // 事件处理代码...
    }, 3000),

三、js提交后显示toast“提交中”没有二次点击的机会

四、web服务器或者数据库中处理多次点击