Can I evaluate the response type of an $.ajax() call in success callback?

前端 未结 3 1738
生来不讨喜
生来不讨喜 2021-01-26 07:04

I am using jQuery to make an AJAX request to a remote endpoint. That endpoint will return a JSON object if there is a failure and that object will describe the failure. If the

相关标签:
3条回答
  • 2021-01-26 07:40

    how about using the complete option?

    $.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');
       },
    
       ...
    });
    
    0 讨论(0)
  • 2021-01-26 07:44

    Have you application generate correct Content-Type headers (application/json, text/xml, etc) and handle those in your success callback. Maybe something like this will 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
    );
    

    Untested, but it's worth a shot.

    0 讨论(0)
  • 2021-01-26 07:52

    By the time it calls your success handler, the data has already been deserialized for you. You need to always return the same data type for any successful result. If there truly is an error, you should probably throw an exception and let it get handled by the error callback instead. This should be able to parse the resulting error and package it for your callback, that is, it will detect that the response did not have 200 OK status and parse the result to obtain the error information.

    0 讨论(0)
提交回复
热议问题