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;
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式