Can someone explain in an easy way how to make jQuery
send actual json
in stead of a querystring
?
$.ajax({
url : url,
dataType : 'json', // I was pretty sure this would do the trick
data : data,
type : 'POST',
complete : callback // etc
});
This will in fact convert your carefully prepared json
to a querystring
. One of the annoying things is that any array: []
in your object will be converted to array[]: []
, probably because of limitations of the querysting
.
-update-
The proper method can be found in the answers below:
$.ajax({
url : url,
dataType : 'json',
contentType: 'application/json; charset=UTF-8', // This is the money shot
data : data,
type : 'POST',
complete : callback // etc
});
Please note that this requires proper CORS headers server-side, and contrary to some examples on the net, Allow-Headers cannot use wildcards. (Allow-Origin can.)
{
Content-Type : 'application/json',
Access-Control-Allow-Origin : '*',
Access-Control-Allow-Headers : 'Content-Type' // You cannot use '*'
}
-update-
Please note that jQuery
will now send TWO requests, one to complete the handshake and one with the actual content. This is for your own security, somehow.
So keep in mind if you want your server to be versatile, using a QueryString sends only one request. Using true JSON sends at least two requests, one for the handshake.
This was messing with my head, so I thought I'd let you (the potential reader) know in advance.
dataType
has no bearing on how the data is sent. It merely specifies what the type of data is you expect to have returned by the call. If you want to indicate to the server what the type of data is you are specifying in thedata
property you need to set thecontentType
property similar tocontentType: "application/json"
– François Wahl Oct 2 '12 at 16:05