JSON formatting (Sending JSON via jQuery AJAX post to Java/Wicket server)

落花浮王杯 提交于 2019-12-17 10:43:01

问题


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:


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.



来源:https://stackoverflow.com/questions/3168401/json-formatting-sending-json-via-jquery-ajax-post-to-java-wicket-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!