求助:Ajax- beforeSend

为了防止出现两次错误,我使用了“发送前”的代码:

hasSent = false

function submit() {
    if (!hasSent)
        $.ajax({
            url: "${createLink(controller:'userInvitation', action:'ajaxUpdate')}",
            type: "POST",
            data: $("#invitationForm").serialize(),
            success: function(data, textStatus, jqXHR) {
                $('#invitationForm')[0].reset();
                $('.thank-you-modal').modal('show');
                hasSent = true;
                console.log(hasSent)
            },

            complete: function() {
                hasSent = false;
                console.log(hasSent)
            }
        });
}

如你所见,只有当hassent=false时,Ajax才会发生。由于某些原因,如果用户在Submit按钮上单击多次(非常快),Ajax也会发生。

To prevent this kind of issue disable the button before sending the ajax and then anable inside the success function

$(mybutton).prop("disabled",true);
// ajax call here

then

success: function(data, textStatus, jqXHR) {
    $(mybutton).prop("disabled",false);
    // code here
}

You can create another flag such as isSending

function submit() {
   if(isSending)
     return;

   isSending = true

   $.ajax({
       // ...
        complete: function() {
            isSending = false;
        }
   });
}

there are two ways you can do this.

1) create a flag and check if the button is pressed. If pressed then do not execute the ajax code

change the flag back once the request is successful, like this

   success:function(...)
            {
               flag=false;
            }

Or you can disable the button at the button click so the request will be carried out and double click situation won't arise. Enable the button on complete like this

 complete:function(..){ $("yourbutton").attr("disabled",false)}