Ajax, prevent multiple request on click

前端 未结 10 2239
忘掉有多难
忘掉有多难 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 05:06

    Use on() and off(), that's what they are there for :

    $('#do-login').on('click', login);
    
    function login(e) {
        e.preventDefault();
        var that = $(this);
        that.off('click'); // remove handler
        $.ajax({
            type: "POST",
            url: "/php/auth/login.php",
            data: $("#login-form").serialize()
        }).done(function(msg) {
            // do stuff
        }).always(function() {
            that.on('click', login); // add handler back after ajax
        });
    }); 
    

提交回复
热议问题