Can I evaluate the response type of the $ .ajax () call on a successful callback?

I am using jQuery to AJAX request to a remote endpoint. This endpoint will return a JSON object if a failure occurs, and this object will describe the failure. If the request is successful, it will return HTML or XML.

I can see how to determine the expected query type in jQuery as part of the call $.ajax()

. Is there a way to determine the type of request in the handler success

?

$.ajax(
    {
        type: "DELETE",
        url: "/SomeEndpoint",
        //dataType: "html",
        data:
            {
                "Param2": param0val,
                "Param1": param1val
            },
        success: function(data) {
                //data could be JSON or XML/HTML
            },
        error: function(res, textStatus, errorThrown) {
                alert('failed... :(');
            }
    }
);

      

0


source to share


3 answers


You have an application that generates the correct Content-Type headers (application / json, text / xml, etc.) and processes them in your callback. Maybe something like this would work?

xhr = $.ajax(
    {
        //SNIP
        success: function(data) {
                var ct = xhr.getResponseHeader('Content-Type');
                if (ct == 'application/json') {
                    //deserialize as JSON and continue
                } else if (ct == 'text/xml') {
                    //deserialize as XML and continue
                }
            },
         //SNIP
);

      



Unconfirmed but worth it.

+4


source


how to use the option complete

?



$.ajax({
   ...

   complete : function(xhr, status) {
   // status is either "success" or "error"
   // complete is fired after success or error functions
   // xhr is the xhr object itself

       var header = xhr.getResponseHeader('Content-Type');
   },

   ...
});

      

+3


source


By the time it calls your success handler, the data has already been deserialized for you. You should always return the same data type for any successful result. If there is indeed an error, you should probably throw the exception and let it handle the error callback. This should be able to parse the error it received and package it for your callback, that is, it detects that the response does not have a 200 OK status and parses the result for information about the error.

0


source







All Articles