weixin_33674976 2017-01-25 11:59 采纳率: 0%
浏览 28

防止重复提交表格

I have a form which has a submit button. If I click this submit button then JSON will be posted to a webservice through AJAX:

$("#msform").submit(function (e) {

    $.ajax({
        url: 'https://example.com/webservice',
        type: 'POST',
        data: formData1,
        crossDomain: true,
        dataType: 'json',
        jsonpCallback: 'callback',
        success: function (data) {
            console.log(data);
        }
    });

});

The webpage will also load and go to another page.. While loading the user can click multiple times on the Submit button, if he does that then for multiple times the AJAX post will be done to the webservice.

I tried this code to fix this but it does not work:

// jQuery plugin to prevent double submission of forms
jQuery.fn.preventDoubleSubmission = function () {
    $(this).on('submit', function (e) {
        var $form = $(this);

        if ($form.data('submitted') === true) {
            // Previously submitted - don't submit again
            e.preventDefault();
        } else {
            // Mark it so that the next submit can be ignored
            $form.data('submitted', true);
        }
    });

    // Keep chainability
    return this;
};

$('#msform').preventDoubleSubmission();

Any idea why double posting is not prevented??

  • 写回答

3条回答 默认 最新

  • weixin_33744141 2017-01-25 12:01
    关注

    The solution is to use a variable called wasSubmitted which verify if ajax request was already sent.

     var wasSubmitted = false;
     $("#msform").submit(function (e) {
        if(!wasSubmitted) {
            wasSubmitted = true;
            $.ajax({
               url: 'https://example.com/webservice',
               type: 'POST',
               data: formData1,
               crossDomain: true,
               dataType: 'json',
               jsonpCallback: 'callback',
               success: function (data) {
                 console.log(data);
               }
           });
           return wasSubmitted;
        }
        return false;
    });
    
    评论

报告相同问题?