0

有没有办法将额外的字段传递给jqXHR对象?这是我的情况:

我正在返回一个HttpResponseMessage这样的:

response.ReasonPhrase = "someString " + Resources.Messages.NoData;
response.StatusCode = HttpStatusCode.NoContent;
return response;

但在某些情况下StatusCode = HttpStatusCode.NoContent;,出于不同的原因,我需要通过另一个:

response.ReasonPhrase = "anotherString " + Resources.Messages.NoMoreData;
response.StatusCode = HttpStatusCode.NoContent;
return response;

因为消息都被本地化(Resources.Messages)到用户语言,我需要一个额外的字段来检查例如它是否等于"someString ""anotherString "或“....”在AJAX success回调中:

$.ajax({
type: 'POST',
url: '/api/testing/test',
data: jobject,
contentType: 'application/json',
success: function (data, status, xhr) {
    if (status == "nocontent" && xhr.statusText.startsWith("someString")) {
        // do something
    }
    if (status == "nocontent" && xhr.statusText.startsWith("anotherString")) {
        // do something
    }

error: function (xhr) {
    debugger;
    if (xhr.responseJSON == 'UnableToParseDateTime') {
        // do something
    }
}
});

奇怪的是,xhr.statusText它不支持xhr.statusText.startsWith(). "someString "所以对or或 "...."的相等检查"anotherString "不起作用。

我注意到responseText在回叫中总是空的success。如果我可以从服务器“填充”那一个会很好。如果没有,我怎么能有一个额外的jqXHR对象字段?或者定义几个新的自定义HttpStatusCode

4

1 回答 1

1

我不确定是否startsWith是标准 javascript,但您始终可以将自己的函数添加到 String 原型中(请参阅此 SO):

if (typeof String.prototype.startsWith != 'function') {
  String.prototype.startsWith = function(str) {
    return this.lastIndexOf(str, 0) === 0;
  };
}

这将允许您使用 . 检查任何字符串startsWith


为了帮助解决添加到 jqXHR 对象的问题,您查看过文档吗?beforeSend您可以在 AJAX 调用的函数中修改 jqXHR 对象。

于 2014-02-24T14:41:22.647 回答