15

I'm using jQuery to post JSON to a Java server, but I think my JSON must be wrong. Here's an example of my data and how I'm sending it:

var lookup = {
    'name': name,
    'description': description,
    'items': [{
        'name': itemName,
        'value': itemValue
    }]
}

$.ajax({
    type: 'post',
    data: lookup,
    dataType: 'json'
});

I'm using Wicket's AbstractAjaxBehavior to receive the data and would like to get a single JSON string that I can parse. When I get a Map of the parameters passed, the keyset looks like this:

items[0][name],
description,
name,
items[0][value],

Obviously I can easily get the values for name and description, but the key for my array of items is messed up. I'm sure it's something simple, but I seem to keep running around the solution. Any suggestions? Thanks!

1
  • Hi Could you post your Wicket AjaxBehavior code. I has a problem (stackoverflow.com/questions/4976244/… ) in that my onRequest() does not seem to be receiving any data. Thanks Commented Feb 12, 2011 at 14:48

1 Answer 1

47

You have to use JSON.stringify:

$.ajax({
    type: 'post',
    data: JSON.stringify(lookup),
    contentType: 'application/json',
    dataType: 'json'
});

You should also specify 'application/json' as the contentType. By default jQuery will serialize objects with application/x-www-form-urlencoded (even if the contentType is application/json'). So you have to do it manually.

EDIT: Key for 'post' should be type, not method.

Sign up to request clarification or add additional context in comments.

3 Comments

jQuery automatically adds the content type as application/json when you specify the dataType as json, doesn't it? I did need to stringify my JSON, though, which solved my problem. Thanks for catching that! Also, if you want your data to come back as a parameter value and not a key, send it like this: data: {'lookup': JSON.stringify(lookup)}
@Jared, no. dataType specifies what you expect the server to send. contentType is the content type you're sending, and jQuery will not change it based on dataType. And {'lookup': JSON.stringify(lookup)} isn't quite correct. If lookup is {foo: "bar"}, that will be url-encoded to something like lookup=%7B%22foo%22%3A%22bar%22%7D That obviously isn't a valid JSON document. When you're posting application/json, you don't use url-encoding. I think this might be connected to you putting method: 'post'. It should be type: 'post'. Method is ignored, and the default is GET.
Note: If you get a "JSON is undefined" error (IE6/7) you'll need to include json.org's latest json.js file in your page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.