发送文件时,Ajax请求会导致页面刷新

时间:2017-10-08 13:44:16

标签: javascript jquery ajax asp.net-mvc

我对ajax没有多少经验,但在将表单数据发送到ASP控制器时遇到了问题。

场景1

将ajax请求中的data设置为

$(this).serialize()

所有表单数据都会发布到控制器,而不会进行任何页面重定向,但会排除随表单一起发送的任何文件。

场景2

将ajax请求中的data设置为

formdata

发布所有表单数据,包括上传的文件,但页面刷新,我不想发生。

这里发生了什么,如何在不刷新页面的情况下发送文件?

代码

// Clear any previous 'success' messages (in case of error)
$('form .btn').on('click', function () {
    $('#result').html('');
});
// Submit form
$('form').submit(function () {
    // Build form data
    var formdata = new FormData(); 
    var fileInput = document.getElementById('fileInput');
    for (i = 0; i < fileInput.files.length; i++) {
        formdata.append(fileInput.files[i].name, fileInput.files[i]);
    }
    // Send ajax request
    $.ajax({
        url: this.action,
        type: this.method,
        data: formdata, // fails to send files when set to $(this).serialize()
        beforeSend: function () {
            $('form .btn').prop('disabled', true);
        },
        success: function (result) {
            $('form .btn').prop('disabled', false)
            $('form .form-control').val('');
            $('#result').html('Thank you. We will contact you shortly.');
            $('.validation-summary-errors ul li').css('display', 'none');
        },
        error: function (result) {
            $('form .btn').prop('disabled', false)
            alert('An error occurred on the server. Please try again. \n\n If this keep happening, please email us at office@auroraglobal.ru');
        }
    });

    return false;
});

1 个答案:

答案 0 :(得分:0)

eventMaking对代码进行微小的更改,你应该这样:

// Clear any previous 'success' messages (in case of error)
$('form .btn').on('click', function () {
    $('#result').html('');
});
// Submit form
$('form').submit(function (event) {
    event.preventDefault(); // this prevents the page from refreshing

    // Build form data
    var formdata = new FormData(); 
    var fileInput = document.getElementById('fileInput');
    for (i = 0; i < fileInput.files.length; i++) {
        formdata.append(fileInput.files[i].name, fileInput.files[i]);
    }
    // Send ajax request
    $.ajax({
        url: this.action,
        type: this.method,
        data: formdata, // fails to send files when set to $(this).serialize()
        beforeSend: function () {
            $('form .btn').prop('disabled', true);
        },
        success: function (result) {
            $('form .btn').prop('disabled', false)
            $('form .form-control').val('');
            $('#result').html('Thank you. We will contact you shortly.');
            $('.validation-summary-errors ul li').css('display', 'none');
        },
        error: function (result) {
            $('form .btn').prop('disabled', false)
            alert('An error occurred on the server. Please try again. \n\n If this keep happening, please email us at office@auroraglobal.ru');
        }
    });
});