【问题标题】:Not receiving Web API HttpResponseMessage in ajax?没有在 ajax 中接收 Web API HttpResponseMessage?
【发布时间】:2013-12-20 18:23:00
【问题描述】:

第一次尝试 Web API,有点困惑。

我已经在 Web Api 中设置了一个基本的删除功能:

public HttpResponseMessage Delete(string id)
{
    HttpResponseMessage response = new HttpResponseMessage();
    response.ReasonPhrase = "User successfully deleted";
    response.StatusCode = HttpStatusCode.OK;

    return response;
}

并通过 jquery ajax 调用它:

deleteUser: function (data) {
    var self = this;
    $.ajax({
        type: "DELETE",
        url: urlPath + data.Id,
        success: function (response) {
            alert("Success: " + response.status + " : " + response.statusText);
        },
        error: function (response) {
            alert("Error: " + response.status + " : " + response.statusText);
        }
    });
}

这行得通... Chrome 开发者工具说 StatusCode: 200 用户已成功删除。

不幸的是,来自 ajax 成功的警报只是说“成功:未定义:未定义”,当在 Chrome 中中断成功函数时,响应变量为空白

如何在 ajax 调用中检索状态代码/消息以显示在屏幕上?

谢谢

【问题讨论】:

  • 而不是response.statusText试试response.responseText

标签: asp.net-mvc jquery asp.net-mvc-5 asp.net-web-api2


【解决方案1】:

jQuery的ajax.success回调函数的参数为​​:

function(PlainObject data, String textStatus, jqXHR jqXHR)

如您所见,第一个参数是原始响应正文。如果您需要 HTTP 状态码和文本,请使用 jqXHR(第三个参数)数据:

success: function(data, status, xhr)
         {
         alert("Success: " + xhr.status + " : " + xhr.statusText);
         }

【讨论】:

    猜你喜欢
    • 2013-03-26
    • 2015-05-22
    • 2013-12-03
    • 2015-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-17
    • 1970-01-01
    相关资源
    最近更新 更多