简体   繁体   中英

What is difference between 'headers:{“Content-Type”:XXX}' and 'contentType:XXX'?

JQuery.ajax provides contentType property to define request data type. Also, content-type could be set by headers property.

Any difference between them?

$.ajax({
    dataType: "json",
    url: url,
    type: 'post',
    data: data,
    contentType: "application/json",
    ...
});

and

$.ajax({
    dataType: "json",
    url: url,
    type: 'post',
    data: data,
    headers: {"Content-Type": "application/json"},
    ...
});

From the jQuery source code. The only usage of contentType option is:

if (s.data && s.hasContent && s.contentType !== false || options.contentType) {
    jqXHR.setRequestHeader("Content-Type", s.contentType);
}

The only usage of headers option is:

for (i in s.headers) {
    jqXHR.setRequestHeader(i, s.headers[i]);
}

The only difference is that when using contentType , jQuery does an extra check to see if your request has any actual data. If not, the content-type header is not added to the headers.

PS: I checked only the code of jQuery2.1.3 , but I doubt its different in any other version

I know this question is quite old, but today we faced an issue related to this topic.

The behavior of jQuery is different between setting contentType property or content-type header if your data contains consecutive questions marks.

Based on the following link, contentType property is the best option. Otherwise, jQuery will assumes that you are trying to use jsonp .

Uncomprehensible jQuery $.ajax() behavior when data contains consecutive question marks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM