sitemap
知识分享网:一个值得你收藏的网站!
当前位置:网站首页 > JavaScript > ajax 实现防止重复提交

ajax 实现防止重复提交

作者:xuhongji发布时间:2020-11-23分类:JavaScript浏览:166评论:0


导读:<!DOCTYPEhtml><html>    <head>   &nb...

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>防止ajax重复提交</title>
    </head>
    <body>
        <button id="btn">提交</button>
        <script>
 
            /**
             * 模拟ajax提交
             * @fn 回调函数
             * */
            function Ajax(fn){
                setTimeout(function(){
                    var data= {result:true,msg:'提交成功!'};
                    fn(data);
                },2000);
            }
            /**
             * btn click 提交事件
             *
             * */
            btn.onclick=function(){
                //检查 按钮是否被锁住,锁住直接rerun
                if(btn.getAttribute('lock')){
                    return;
                }
                //上锁
                btn.setAttribute('lock',1);
                //更改状态
                btn.innerText='提交中...';
                //模拟ajax提交
                Ajax(function(data){
                    //请求成功
                    if(data.result){
                        console.log('请求成功');
                        //请求成功解锁
                        btn.setAttribute('lock',"");
                        //还原状态
                        btn.innerText='提交';
                    }else{
                        console.log('请求失败');
                        //请求失败解锁
                        btn.setAttribute('lock',"");
                        //还原状态
                        btn.innerText='提交';
                    }
                });
            }
        </script>
    </body>
<p>
    </html>
</p>
 
<p>

    

<span style="color:#333333;font-family:-apple-system, "font-size:16px;background-color:#FFFFFF;">1.提交数据之前判断当前提交按钮是否存在lock锁</span>

<span style="color:#333333;font-family:-apple-system, "font-size:16px;background-color:#FFFFFF;">2.在ajax提交之前给提交按钮上锁</span>

<span style="color:#333333;font-family:-apple-system, "font-size:16px;background-color:#FFFFFF;">3.ajax成功之后或者失败之后解锁</span>

</p>



欢迎 发表评论:

JavaScript排行
«   2021年1月   »
123
45678910
11121314151617
18192021222324
25262728293031
标签列表
网站分类
文章归档
最近发表
推荐文章