JSON 格式(通过 jQuery AJAX post 将 JSON 发送到 Java/Wicket 服务器)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3168401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 17:03:31  来源:igfitidea点击:

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

javajqueryajaxjsonwicket

提问by Jared

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:

我正在使用 jQuery 将 JSON 发布到 Java 服务器,但我认为我的 JSON 一定是错误的。这是我的数据以及我如何发送数据的示例:

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:

我正在使用 Wicket 的 AbstractAjaxBehavior 来接收数据,并希望获得我可以解析的单个 JSON 字符串。当我得到传递参数的 Map 时,键集如下所示:

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!

显然,我可以轻松获取 name 和 description 的值,但是我的项目数组的键搞砸了。我确信这很简单,但我似乎一直在寻找解决方案。有什么建议?谢谢!

采纳答案by Matthew Flaschen

You have to use JSON.stringify:

你必须使用 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.

您还应该将“application/json”指定为 contentType。默认情况下,jQuery 将使用 application/x-www-form-urlencoded 序列化对象(即使 contentType 是 application/json')。所以你必须手动完成。

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

编辑:'post' 的键应该是类型,而不是方法。