Wednesday, September 5, 2012

Jquery Ajax And POSTing JSON

This snippet of code:

var ajax_params = {
  type: 'POST',
  url: dst_url,
  contentType: 'application/json',
  dataType: 'json',
  data: dto_obj,
  error: function(jqXHR, textStatus, errorThrown) {
  success: function (data, textStatus, jqXHR) {

_still_ gives me encoded gibberish on the server, not JSON. But the Content-Type header seems to be correct, from debugger: Content-type=[application/json, null].

Good and necessary jQuery debug technique: step into the $.ajax() call and look at the calculated parameters.

But it's easier to use XMLHttpRequest directly.


Conflicting answers on Stack Overflow:

answer1 says don't pass a string, pass the object; wrong, apparently.
answer2 says pass the serialized string.

Guess which answer I happened to read first.

So; to be clear, this is what works: "data: JSON.stringify(dto_obj)". 

No comments:

Post a Comment