views:

549

answers:

4

Hi,

Is there any way I can evaluate the returned content type of a jquery ajax request and do different things depending on the content type?

For example if the conten type is html I'd like to append this to a certain div on my page. If the content type is text/javascript I'd like to just evaluate the javascript. If the content type is JSON I'd like to process the returned JSON data according to my needs.

Not sure if that is possible.

A: 

I do not think this is possible since you must either determine ahead of time what the data type of the response will be or if you leave the data type parameter blank in your $.ajax call, jQuery will either return xml or plain text.

In order to achieve what you want, you would have to do some type of detection yourself to determine if the response is json/javascript/html.

Check this page http://docs.jquery.com/Ajax/jQuery.ajax#options and look under the dataType parameter. That is where I got the information from.

T B
A: 

Did you ever solve this? I would like to do the same thing.

Fredrik
You can check out the jQuery taconite plugin. It filters out all XML answers for some custom processing. The code is very easy to understand and it shows how it can be done
MarcS
A: 

Yes, it is possible...

$.ajax({

  // Set the URL, method, parameters, yada, yada, yada

  complete:function(xhr, stat) {
    var typ = xhr.contentType;
    var res = xhr.responseText;

    alert("Type: " + typ);
  }
});
Josh Stodola
+1  A: 

var xhr = $.post(action, params, function(data) {
if (xhr.getResponseHeader("Content-Type") == 'application/pdf') { ... }
});

ihar.khadarovich