You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core中AJAX提交后跳转到JSON页面问题求助

解决AJAX提交后跳转至JSON页面的问题

核心问题分析

表单默认的同步提交行为未被阻止,同时AJAX请求缺少FormData提交必需的配置项,导致页面跳转。

具体修复步骤

1. 阻止表单默认提交行为

修改submitHandler,在调用submitAJAX后添加return false;,彻底阻断表单的默认提交流程:

submitHandler:function(form){
    debugger;
    if (isDuplicate) {
        return false;
    } else {
        submitAJAX(form);
        // 阻止表单默认提交
        return false;
    }
    debugger;
}

2. 完善AJAX请求配置

由于使用FormData提交包含文件的表单,必须添加processData: false和contentType: false两个配置项,避免jQuery自动处理数据导致请求格式错误:

$.ajax({
    url: "/Product/Create",
    data: fromData,
    method: "post",
    dataType: "json",
    // 新增以下两项配置
    processData: false,
    contentType: false,
    success: function (response) {
        var data = response;
        if (data.success) {
            $("#modal_sm").modal("hide");
            toastr.success("Data success input");
            window.location.reload();
        }
        else {
            $("#modal_sm").modal("hide");
            toastr.error("Data failed input");
        }
    },
    // 可选:添加错误处理,排查请求问题
    error: function(xhr, status, error) {
        console.error("AJAX请求失败:", error);
        toastr.error("请求出错,请检查控制台");
    }
});

3. 验证控制器返回格式

确保Create方法返回标准的JsonResult,格式如下:

[HttpPost]
public IActionResult Create(ProductViewModel model)
{
    // 数据插入逻辑...
    if (插入成功)
    {
        return Json(new { success = true });
    }
    else
    {
        return Json(new { success = false });
    }
}

额外注意事项

  • 确认页面中引入的jQuery版本与validate插件兼容,避免因版本问题导致事件绑定失效。
  • 检查表单标签是否未设置action属性,若设置了action,即使阻止默认行为也可能出现意外跳转,建议移除表单的action属性。

内容的提问来源于stack exchange,提问作者Andi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 08:47:21