dataType 'application/json' vs. 'json'
javascript, jquery, json
Solution
`dataType` takes json, it means the request expects a `json` response.
`contentType` takes `application/json`, it means the request is sending `json` data
You can send as well as expect json in a request e.g.
$.ajax({
type : "POST",
url : url,
contentType : "application/json",
dataType: 'json',
data: JSON.stringify({some: 'data'}),
success : function(data) {
// do something
},
error : function(data) {
// do something else
}
});
here you're sending json and expecting xml
$.ajax({
type : "POST",
url : url,
contentType : "application/json",
dataType: 'xml',
data: JSON.stringify({xmlfile: 'file.xml'}),
success : function(data) {
// do something
},
error : function(data) {
// do something else
}
});
and here you're sending `x-www-form-urlencoded`(jQuery automatically sets this for you), and expect json back
$.ajax({
type : "POST",
url : url,
dataType: 'json',
data: {id: '1'},
success : function(data) {
// do something
},
error : function(data) {
// do something else
}
});
contentType sets the `ContentType` HTTP request header, telling the server that the body of this request is of the given type. dataType sets the `Accept` header to tell the server that this is the type of response we want e.g.
Accept:application/json, text/javascript, */*; q=0.01
but regardless of what type of response the server sends jQuery will still attempt to parse it as whatever type you set in the dataType field.
Problem
Possible Duplicate: $.ajax - dataType I am using jQuery 1.8.2, and for some reason `'application/json'` does not work, but `'json'` works as `dataType` to a standard `jquery` `ajax` call. Is this a glitch? A version related difference? or is there an established difference between the two? ``` $(document).ready(function() { $.ajax({ type : "POST", url : '<c:url value="/url.htm" >', //dataType : "application/json", <-- does not work dataType: 'json' // <-- works success : function(data) { // do something }, error : function(data) { // do something else } }); }); ```