jQuery: The Write Less, Do More JavaScript Library

Specifying the Data Type for AJAX Requests

From jQuery JavaScript Library

Jump to: navigation, search

The $.ajax function gives you the ability to specify a dataType parameter, which gives jQuery a hint as to what to expect in the response from the server. Based on this hint, jQuery processes the response data and passes it as the first argument to your success callback function (if provided). You may specify the dataType as a key/value pair in the lone argument passed to $.ajax. Supported types are:

  • "xml": Treat the response as an XML document that can be processed via jQuery.
  • "html": Treat the response as HTML (plain text); included script tags are evaluated.
  • "script": Evaluates the response as JavaScript and evaluates it.
  • "json": Evaluates the response as JSON and sends a JavaScript Object to the success callback

Using the right MIME type

It's important that the server handling the request sends the right MIME type in the response (eg. xml as "text/xml"). That is, if you specify the $.ajax dataType option to be "xml", make sure your server sends content with the "text/xml" MIME type. Sending the wrong MIME type will prohibit jQuery from correctly managing the data returned in the response, and could cause unexpected problems in your script.

When loading XML files locally, e.g. a CD-ROM etc., the data received by Internet Explorer is plain-text, not text/xml. In this case, use the dataType parameter to load the xml file as text, and parse the returned data within the succes function

 $.ajax({
   url: "data.xml",
   dataType: ($.browser.msie) ? "text" : "xml",
   success: function(data){
     var xml;
     if (typeof data == "string") {
       xml = new ActiveXObject("Microsoft.XMLDOM");
       xml.async = false;
       xml.loadXML(data);
     } else {
       xml = data;
     }
     // Returned data available in object "xml"
   }
 }); 

Handling the JSON data type

If you specify the dataType option to be "json" for an $.ajax request, jQuery will take the responseText of the XMLHttpRequest, and turn it into an object and pass it as the first argument to your success callback function. You can then maniuplate it as a JavaScript object directly. This is opposed to specifying the dataType option as, for example, "html", and having jQuery pass a string to your success callback as the first argument.