Jquery how to check response type for ajax call

How to determine the response type of an ajax call in jQuery? From time to time, the server sends a json response, and sometimes it sends only html for display. Now i'm using

if(response.indexOf('Error')) //popup error message else response.username response.address 
+60
jquery ajax
18 Sep '10 at 11:46
source share
5 answers

You can try:

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

It mainly uses indexOf as well, but seems more reliable.

+103
Sep 18 '10 at 11:54 on
source share

You can just use a simple javascript 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 do not need to write 2 additional parameters in the callback.

+14
Jul 05 '12 at 10:17
source share

The answers above did not 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 }} 
+8
Dec 09 '11 at 12:57 on
source share

If the response is processed 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 jQuery.ajax documentation :

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

+6
Sep 22 '14 at 9:28
source share

To accept a JSON response, you can set the response type as JSON. I usually develop my server side code so that they always return a JSON response. If for some reason this does not help, I would get an error in my AJAX call for the wrong JSON format, and I can treat the response from the server as non-JSON.

 error: function(response, status, xhr){ // do something with the reply. } 
0
Sep 18 '10 at 11:58
source share



All Articles