Ajax, prevent multiple request on click

前端 未结 10 2238
忘掉有多难
忘掉有多难 2020-11-28 04:10

I\'m trying to prevent multiple requests when user click on login or register button. This is my code, but it doesn\'t work. Just the first time works fine, then return fals

10条回答
  •  北海茫月
    2020-11-28 04:44

    This function can help you with control multi Ajax requests and it's has timeout function which can return flag status to 0 after ex. 10sec (In case the server took more than 10 seconds to respond)

    var Request_Controller = function(Request_Name = '', Reactivate_Timeout = 10000)
    {
        var a = this;
        a.Start_Request = function(){
            if(window.Requests == undefined){
                window.Requests = {};
            }
            window.Requests[Request_Name] = {'Status' : 1, 'Time': + new Date()};
        }
    
        a.End_Request = function(){
            if(window.Requests == undefined){
                window.Requests = [];
            }
            window.Requests[Request_Name] = undefined;
        }
    
        a.Is_Request_Running = function(){
            if(window.Requests == undefined || window.Requests[Request_Name] == undefined){
                return 0;
            }else{
                var Time = + new Date();
                // Reactivate the request flag if server take more than 10 sec to respond
                if(window.Requests[Request_Name]['Time'] < (Time - Reactivate_Timeout)) 
                {
                    return 0;
                }else{
                    return 1
                }
            }
        }
    }
    

    To use it:

    var Request_Flag = new Request_Controller('Your_Request_Name');
    if(!Request_Flag.Is_Request_Running()){
    
        Request_Flag.Start_Request();
    
        $.ajax({
            type: "POST",
            url: "/php/auth/login.php",
            data: $("#login-form").serialize(),
            success: function(msg) {
                //stuffs
            },
            complete: function() {
                Request_Flag.End_Request();
            }
        }); 
    }
    

提交回复
热议问题