jquery - 如何将错误消息返回给 Ajax 调用
问题描述
我有一个新的 Mvc Core 应用程序。我使用 jquery 对我的控制器进行 ajax 调用。如果控制器中出现异常,我正在尝试返回错误消息。这是我的代码示例:
public async Task<IActionResult> UpdateAllocations([FromBody]AllocationsDto allocationsDto)
{
...
catch (Exception ex)
{
Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
return Json(new { success = false, responseText = ex.Message });
}
...
$.ajax({
type: "POST",
url: "/Allocation/UpdateAllocations",
data: JSON.stringify(allocationData),
contentType: "application/json; charset=utf-8",
dataType: "json"
})
.done(function (data) {
})
.fail(function (xhr, status, error) {
displayError("The ajax call to UpdateAllocations() action method failed:",
error, "Please see the system administrator.");
});
但是error参数是空的,status只有一个单词“error”以及xhr.statusText。如何返回我自己的自定义文本,在这种情况下为 ex.Message?
解决方案
类型:Function(jqXHR jqXHR, String textStatus, String errorThrown) 请求失败时调用的函数。该函数接收三个参数:jqXHR(在 jQuery 1.4.x 中,XMLHttpRequest)对象,一个描述发生的错误类型的字符串和一个可选的异常对象(如果发生)。第二个参数(除了 null)的可能值是“timeout”、“error”、“abort”和“parsererror”。发生 HTTP 错误时,errorThrown 会接收 HTTP 状态的文本部分,例如“未找到”或“内部服务器错误”。
您需要从第一个参数的 responseJSON 中获取消息。
.fail(function (xhr, status, error) {
displayError("The ajax call to UpdateAllocations() action method failed:",
xhr.responseJSON.responseText, "Please see the system administrator.");
});
推荐阅读
- tensorflow - 除了 c_api.cc 中的断点,TensorFlow gdb 是否支持断点?
- computer-vision - 欧拉角在接近零度时翻转
- flutter - Flutter 两指滑动手势识别器
- sql - 将 NULL 替换为空白值 (SQL Server)
- java - Java - Spring 的 ReactorNettyWebSocketClient 线程安全吗?
- python - 有没有办法将变量从循环传递到 find_element_by_xpath 正则表达式?
- javascript - 在预定义的时间段内滚动到底部
- excel - 使用 select case 语句评估多列
- c - 使用 sqlite3 将某些数据分配给结构
- matplotlib - AttributeError:“轴”对象在 matplotlib 中没有属性“get_proj”