为什么在页面加载后触发Ajax请求

时间:2016-03-17 12:38:31

标签: javascript jquery ajax

我希望在任何表单字段中更改任何内容后发送Ajax请求,但在下面的代码中,Ajax请求也会在页面加载后触发。

window.submitting = false;
$('form#AddForm').submit(function() {
    window.submitting = true;
});

var timeoutId;
var saveHandler = function() {
    console.log('Change');

    if (window.submitting)
        return false;

    clearTimeout(timeoutId);
    timeoutId = setTimeout(function() {
        // Runs 1 second (1000 ms)
        autoSave();
    }, 1000);
};

$('form input, form textarea, form select').bind('input propertychange change', saveHandler);

function autoSave() {
    // unbind events
    $('form input, form textarea, form select').unbind('input propertychange change');
    $.ajax({
        type: "POST",
        data: $('form#AddForm').serialize() + '&autosave=true',
        beforeSend: function(xhr) {
            // Let them know we are saving
            console.log('Saving........');
        },
        success: function(data) {
            alert('done');
            // bind events back
            $('form input, form textarea, form select').bind('input propertychange change', saveHandler);
        },
        error: function(){
        //alert('error');
            // bind events back even if reqeust fail
            $('form input, form textarea, form select').bind('input propertychange change', saveHandler);
        },
    });
}

0 个答案:

没有答案