防止ajax重复请求

在留言,评论回复时,或者下载加载更多,容易出现多次请求接口的情况

 <!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta charset="utf-8">
    </head>
    <body>
        <input type="button" id="btnTest" value="测试"/>
        <script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
        <script>
             lock=false;
            $('#btnTest').click(function() {
                if(lock){
                    console.log('wait');
                    return;
                }
                lock=true;
                this.ajaxRequest_ = $.ajax({
                    type: "POST",
                    url: "index.php",
                    success: function(msg) {
                        lock=false;
                        console.log(msg);
                    },
                    error: function(msg){
                        lock=false;
                        console.log(msg);
                    }
                })
            });
        </script>
    </body>
</html>
<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta charset="utf-8">
    </head>
    <body>
        <input type="button" id="btnTest" value="测试"/>
        <script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
        <script>
            $('#btnTest').click(function() {
                if (this.ajaxRequest_ != undefined && this.ajaxRequest_.readyState < 4) {
                    console.log('wait');
                    return false;
                }
                this.ajaxRequest_ = $.ajax({
                    type: "POST",
                    url: "index.php",
                    success: function(msg) {
                        console.log(msg);
                    }
                })
            });
        </script>
    </body>
</html>
<?php
sleep(5);
echo 123;

参考地址   https://blog.csdn.net/Crystalqy/article/details/79078741

posted @ 2018-07-20 15:26  za_szybko  阅读(255)  评论(0编辑  收藏  举报