Tuesday, January 27

jQuery ajax, to send JSON instead of QueryString

You need to use JSON.stringify to first serialize your object to JSON, and then specify the content-type so your server understands it's JSON. This should do the trick:

$.ajax({
    url: url,
    type: "POST",
    data: JSON.stringify(data),
    processData: false,
    contentType: "application/json; charset=UTF-8",
    complete: callback
});

Note that not all browsers support the JSON object, and although jQuery has .parseJSON, it has no stringifier included; you'll need another polyfill library.

Setting processData to false isn't necessary since JSON.stringify already returns a string.

No comments:

Post a Comment