weixin_33701617 2015-07-07 19:27 采纳率: 0%
浏览 28

Ajax执行多次

I have written an ajax post request however it seems to be executing multiple times. The first time I click the button it will execute only once, however the second time I click the button it will run through the code twice, three times will execute three times and so on. I am not sure what is causing this problem, here is my ajax post request. If any other information is needed I will happily provide.

$(document).ready(function () {
$('#postEditDatasource').click(function (event) {
    //serialise and assign json data to hidden field
    $('#dsDeletedDP').val(JSON.stringify(deleted));
    $('#dsEditedDP').val(JSON.stringify(editDPArr));

    //get the form
    var form = $('#__dsAjaxAntiForgeryForm');

    var URL = 'Settings/EditDatasource';

    $('#__dsAjaxAntiForgeryForm').on('submit', function () {
        $.ajax({
            url: URL,
            data: form.serialize(),
            type: 'POST',
            success: function (result) {

                reloadPostEditAction($('#dsID').val());

                if (deletedDatapoints != null) {
                    DeleteFromTable(deleted);
                }

                //clear all values from hidden inputs
                $('input:hidden').each(function () {
                    if ($(this).attr('name') != '__RequestVerificationToken' && $(this).attr('id') != 'dsID') {
                        $(this).val('');
                    }
                });

                $('#dsEditedDP').val('');

                ShowDatasourcePostAlert('#successPost', 3000);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                //alert(jqXHR + ', ' + textStatus + ', ' + errorThrown);
                ShowDatasourcePostAlert('#successPost', 3000);
            }
        })
        return false;
    })
});
})
  • 写回答

2条回答 默认 最新

  • weixin_33690367 2015-07-07 19:33
    关注

    The problem you are experience is expected from your code.

    Every time this event happens: $('#postEditDatasource').click(function (event) {

    You add a new event here: $('#__dsAjaxAntiForgeryForm').on('submit', function () {

    So, the events compound. Every time you click the #postEditDatasource element, assign a submit event handler to #__dsAjaxAntiForgeryForm

    In other words, the first time you click, you have one submit event handler. The second time you click, you have two submit event handlers. The third time you click, you will have three submit event handlers, and so on...

    You can easily fix this by removing the submit event handler first (by using .off(), like this $('#__dsAjaxAntiForgeryForm').off().on('submit', function () {

    评论

报告相同问题?