weixin_33737774 2016-02-09 17:32 采纳率: 0%
浏览 19

AJAX多种表单提交

I'm not a Javascript master however I tried hard to prevent this. This script keeps randomly sending multiple posts. I couldn't manage to stabilize it. Usually works fine and sends one post per click. However sometimes it just decides that it should be posted like 5-6 times... Note that using async: false did not really make any difference. And it prevents me from disabling the button after the submission and its not because of "number of clicks" either. Thanks in advance!

$('#submit').click(function () {
    $('#submit').attr("disabled", true);
    var personal_text_data = document.getElementById('personal_text').value;
    var lang_option_data = document.getElementById('language_option').checked;
    $.ajax({
        type: "POST",
        url: 'send.php',
        cache: false,
        // async: false,
        data: ({
            notification_type: notification_type_data,
            customer_id: customer_id_data,
            personal_text: personal_text_data,
            language_option: lang_option_data
        }),
        success: function () {
            delete customer_id_data;
            delete personal_text_data;
            delete notification_type_data;
            delete lang_option_data;
            location.reload();
        }
    });
});
  • 写回答

1条回答 默认 最新

  • ??yy 2016-02-09 17:38
    关注

    Use e.preventDefault(); to avoid the ajax submission and normal form submit from happening. Also change the click event and make it $('[yourForm]').submit().

    $('[selectorToYourForm]').submit(function (e) {
        $('#submit').prop("disabled", true);
        e.preventDefault();
        var personal_text_data = document.getElementById('personal_text').value;
        var lang_option_data = document.getElementById('language_option').checked;
        $.ajax({
            type: "POST",
            url: 'send.php',
            cache: false,
            // async: false,
            data: ({
                notification_type: notification_type_data,
                customer_id: customer_id_data,
                personal_text: personal_text_data,
                language_option: lang_option_data
            }),
            success: function () {
                location.reload();
            }
        });
    });
    
    评论

报告相同问题?