ASP.NET Core项目中AJAX的Success/Error回调函数未执行问题求助
问题根因
你的AJAX回调未触发是因为表单默认提交行为中断了AJAX请求生命周期:
- 你将提交按钮放在
<form>标签内部,且未给<button>指定type属性,浏览器默认会将该按钮识别为submit类型 - 点击按钮时会先触发你绑定的click事件发送AJAX请求,随后立刻触发form原生提交行为,页面跳转/刷新直接中断了还在等待响应的AJAX请求,因此success和error回调都没有机会执行
解决方案(任选其一即可)
方案1:阻止按钮点击的默认提交行为
在你的点击事件回调中增加阻止默认行为的逻辑,修改JS代码如下:
$("#button").click(function (e) { // 增加事件参数e e.preventDefault(); // 新增这行,阻止form默认提交 var orderedQuantity = $("#txt").val(); var orderId = $("#orderId").val(); var inventoryorderId = $("#inventoryorderId").val(); var inventoryId = $("#inventoryId").val(); var data = { orderId: orderId, inventoryorderId: inventoryorderId, inventoryId: inventoryId, orderedQuantity: orderedQuantity, }; $.ajax({ type: 'POST', url: '@Url.Action("EditItem", "Orders")', data: data, dataType: "json", success: function (result) { alert(result); var url = '@Url.Action("Index", "Orders")'; window.location.href = url + "?custEmail=xyz@rrr.org"; }, error: function (error) { alert(error); } }); });
方案2:修改按钮类型为普通按钮
直接给按钮指定type="button",让浏览器不再将它识别为表单提交按钮:
<button id="button" type="button">Update</button>
额外优化建议
你当前AJAX配置指定了dataType: "json",要求服务端返回合法JSON格式,而控制器中存在return Json("")的写法,部分低版本jQuery会将空字符串判定为非法JSON,触发静默的解析错误。可以统一将空返回修改为标准JSON结构,比如:
return Json(new { success = true, msg = "" });
内容的提问来源于stack exchange,提问作者user4912134
相关产品推荐
相关产品推荐

