jquery - 如何向 Ajax 调用返回错误消息

标签 jquery ajax asp.net-core-mvc

我有一个新的 Mvc Core 应用程序。我使用 jquery 对我的 Controller 进行 ajax 调用。我试图在 Controller 出现异常时返回错误消息。这是我的代码示例:

    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??

最佳答案

Type: Function( jqXHR jqXHR, String textStatus, String errorThrown ) A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error."

您需要从第一个参数的responseJSON中获取消息。

.fail(function (xhr, status, error) {

       displayError("The ajax call to UpdateAllocations() action method failed:",
                    xhr.responseJSON.responseText, "Please see the system administrator.");
});

关于jquery - 如何向 Ajax 调用返回错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56550572/

相关文章:

c# - 如何使用 ASP.NET Core 项目在 Visual Studio 2017 中创建指向图像的符号链接(symbolic link)?

c# - 如何从 EF Core 中的父实体中删除子实体?

javascript - 如何使用 Jquery 仅在图标单击时显示日期选择器?

html - jQuery.noConflict() 不适用于弹出框

javascript - 匹配没有标签的 DOM 文本?

java - 如何根据先前的选择从下拉列表中进行选择?

javascript - 来自 ajax 调用的 JSON 输入意外结束

javascript - Ajax 和 json_encode 在 Firefox 中回显文本而不是 json

asp.net-mvc - ASP.Net 5 MVC6 select taghelper 产生错误的输出

javascript - 保护客户端->数据库游戏