Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dataType 'application/json' vs. 'json' [duplicate]

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
        }
    });
});
like image 351
Isaac Avatar asked Dec 06 '12 02:12

Isaac


2 Answers

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.

like image 179
Musa Avatar answered Sep 17 '22 23:09

Musa


"application/json" is the correct mime type for json. The jquery dataType field, however, is expecting one of the following strings:

"xml"
"html"
"script"
"json"
"jsonp"
like image 34
Sam Dufel Avatar answered Sep 19 '22 23:09

Sam Dufel