开发者

jquery how to check response type for ajax call

How can I determine the response type of ajax call 开发者_运维问答in Jquery? At times, the server sends json response and at times it sends only the html for display purposes. Right now I am using

if(response.indexOf('Error'))
  //popup error message
else
 response.username
 response.address


You can try it like:

$.ajax({
  type: "POST",
  url: "your url goes here", 
  data: "data to be sent", 
  success: function(response, status, xhr){ 
    var ct = xhr.getResponseHeader("content-type") || "";
    if (ct.indexOf('html') > -1) {
      //do something
    }
    if (ct.indexOf('json') > -1) {
      // handle json here
    } 
  }
});

Basically it is also using indexOf but it seems more reliable.


You can simply use javascript's easy method to check the type

i.e.

if(typeof response=="object")
{
 // Response is javascript object
}
else
{
 // Response is HTML
}

If you use this method you don't have to write 2 extra parameter in the success callback.


If the response is parsed as JSON, the jqXHR object will have a responseJSON property.

$.ajax(
    // ...
).done(function(data, textStatus, jqXHR) {
    if (jqXHR.responseJSON) {
        // handle JSON
    } else {
        // handle html
    }
}).fail(function(jqXHR, textStatus, errorThrown) {
    if (jqXHR.responseJSON) {
        // handle JSON
    else {
        // handle html
    }
})

From the jQuery.ajax documentation:

If json is specified, the response is parsed using jQuery.parseJSON before being passed, as an object, to the success handler. The parsed JSON object is made available through the responseJSON property of the jqXHR object.


The answers above didnt work for me so I came up with this solution:

success: function(data, textStatus , xhr) {
if(xhr.responseXML.contentType == "text/html") {
    //do something with html
    }
else if(xhr.responseXML.contentType == "application/json") {
    //do something with json
    }}


To accept a JSON reply, you can set the reply type as JSON. I usually design my server side code so they always return JSON reply. In the event it fails to do so for whatever reason, I would get an error in my AJAX call for having incorrect JSON format and I can process the reply from server as not being non JSON.

error: function(response, status, xhr){ 
// do something with the reply.
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜