tags:

views:

79

answers:

2
+3  Q: 

$.ajax - dataType

what is the difference between

contentType: "application/json; charset=utf-8",
dataType: "json",

vs.

contentType: "application/json",
dataType: "text",
+4  A: 
  • contentType is the header sent to the server, asking for a particular format.
    • Example: give me json or give me XML
  • dataType is you telling jQuery what kind of response to expect.
    • Expecting JSON, or XML, or HTML, etc....the default it for jQuery to try and figure it out.

The $.ajax() documentation has full descriptions of these as well.

In your particular case, the first is asking for the response to be in utf-8, the second doesn't care. Also the first is treating the response as a javascript object, the second is going to treat it as a string.

So the first would be:

success: function(data) {
  //get data, e.g. data.title;
}

The second:

success: function(data) {
  alert("Here's lots of data, just a string: " + data);
}
Nick Craver
which one is the more preferred way or most recommend.
Abu Hamzah
@Adu - No direct answer for that, depends what you want to do with the result...they're doing 2 different things. Ideally, unless it's a very simple result, you probably want to be dealing with JSON in which case the first one would be easier.
Nick Craver
+2  A: 

as per docs:

  • "json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
  • "text": A plain text string.
SilentGhost