我希望能够在ajax调用成功时提交表单,而在失败时阻止提交。有什么方法可以执行但不能两次调用控制器吗?

控制器退货

return File(excelPackage.GetAsByteArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);


AJAX电话

//Form contains action : /api/Excel/DownloadExcel
$('#form').on('submit', function (e) {
    var submit = false;
    $.ajax({
        url: '/api/Excel/DownloadExcel',
        type: 'POST',
        data: $('#form').serialize(),
        async: false
    })
        .done(function () {
            submit = true;
        })
        .fail(function (response) {
            displayErrorMessage(response.status, response.responseText);
        });
    return submit;
});

最佳答案

由于您具有表单并提交,因此默认情况下它将基于action属性向服务器发送请求。

问题是您的表单发送了一个请求,然后您还向服务器发送了另一个请求。因此,您在控制器中的操作收到了2个请求。

在您的情况下,建议在将请求发送到服务器之前调用方法preventDefault

$('#form').on('submit', async function (e) {
    // add this line to your event to prevent submiting by default
    e.preventDefault();

    try {
        var file = await $.ajax({
            url: '/api/Excel/DownloadExcel',
            type: 'POST',
            data: $('#form').serialize(),
            async: false
        });

        console.log(file);

        return true;
    } catch (response) {
        displayErrorMessage(response.status, response.responseText);

        return false;
    }
});


我还重写了您的活动以使其清楚。



如果要允许不提交就下载文件,则可以重写事件:

$('#form').on('submit', function (e) {
    e.preventDefault();

    return false;
});

$('#download').on('click', async function (e) {
    e.preventDefault();

    // your ajax code goes here...
});

09-25 17:02
查看更多