Reputation: 29291
$.ajax({
url: Settings.get('serverURL') + 'PlaylistItem/CreateMultiple',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(newItems)
});
I'm explicitly setting the contentType of the AJAX request to indicate JSON is being sent across the wire. However, I seem to be inconsistent in my application of contentType across my code and all AJAX requests are working properly.
Is it necessary or beneficial to be explicit with the JSON contentType or should I omit it?
Upvotes: 0
Views: 847
Reputation: 1183
According to the JQuery documentation
contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8') Type: String When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent). The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding.
In practice I have found it beneficial to explicitly state it either in $.ajax or through
$.ajaxSetup({
contentType: "application/json; charset=utf-8"
});
as application/x-www-form-urlencoded has caused me the occasional null value in MVC action parameters as per this article
http://haacked.com/archive/2010/04/15/sending-json-to-an-asp-net-mvc-action-method-argument.aspx/
Upvotes: 1