سؤال

Is there a way to pass an extra field to the jqXHR object? Here my situation:

I'm returning a HttpResponseMessage like so:

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

But there are some cases I need to pass another StatusCode = HttpStatusCode.NoContent;, for a different reason:

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

Because the messages are all localized (Resources.Messages) to the users language, I need an extra field to check for example if it equals to "someString " or "anotherString " or "...." in the AJAX success call back:

$.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
    }
}
});

The weird thing is, is that xhr.statusText doesn't support xhr.statusText.startsWith(). So equality checks on "someString " or "anotherString " or "...." doesn't work.

I've noticed that responseText is always empty in the success call back. If I can 'fill' that one from the server would be nice. If not, how can I have an extra field for the jqXHR object? Or define a few new custom HttpStatusCode?

هل كانت مفيدة؟

المحلول

I'm not sure if startsWith is standard javascript, but you can always add your own function to the String prototype (see this SO):

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

Which will allow you to check any String with startsWith.


To help with the question on adding to the jqXHR object, have you taken a look at the docs? You can modify the jqXHR object in the beforeSend function of the AJAX call.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top