0

第一次尝试 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 调用中检索状态代码/消息以显示在屏幕上?

谢谢

4

1 回答 1

2

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

function(PlainObject data, String textStatus, jqXHR jqXHR)

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

success: function(data, status, xhr)
         {
         alert("Success: " + xhr.status + " : " + xhr.statusText);
         }
于 2013-12-05T13:22:51.923 回答