首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何将错误消息返回给Ajax调用

如何将错误消息返回给Ajax调用
EN

Stack Overflow用户
提问于 2019-06-12 03:29:50
回答 1查看 2.3K关注 0票数 1

我有一个新的Mvc核心应用程序。我使用jquery对我的控制器进行ajax调用。我正在尝试返回一个错误消息,以防控制器中出现异常。下面是我的代码示例:

代码语言:javascript
复制
    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 });

            }

..。

代码语言:javascript
复制
  $.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??

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-12 10:43:31

函数类型:

( jqXHR jqXHR,String textStatus,String errorThrown )请求失败时调用的函数。该函数接收三个参数: jqXHR (在jQuery 1.4.x,XMLHttpRequest中)对象、描述所发生的错误类型的字符串和一个可选的异常对象(如果发生的话)。第二个参数(除了null之外)的可能值是"timeout“、"error”、"abort“和"parsererror”。当HTTP错误发生时,errorThrown接收HTTP状态的文本部分,例如“未找到”或“内部服务器错误”。

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

代码语言:javascript
复制
.fail(function (xhr, status, error) {

       displayError("The ajax call to UpdateAllocations() action method failed:",
                    xhr.responseJSON.responseText, "Please see the system administrator.");
});
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56550572

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档