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

前端 未结 3 1767
生来不讨喜
生来不讨喜 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: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.

提交回复
热议问题