【发布时间】:2012-02-04 04:09:41
【问题描述】:
对于带有 RESTful 后端的 web 应用程序,我使用 jquery 的 $post 将一些 json 发布到服务器。现在令我惊讶的是,json 被填充在请求表单数据的参数键中,而不是在请求正文中。我能想到一些other ways to do it,但问题是为什么它不能像我预期的那样工作。
在服务器上我使用 scalatra 并打印一些请求信息:
println("Request received:")
println(fromInputStream(request.getInputStream).getLines().mkString)
println("--------------")
println(request.getParameterMap.toString)
println("==============")
现在做一个我认为正确的简单卷曲:
curl -X POST http://localhost:8080/x -H "Content-Type: application/json" -d '{"a":"b"}'
生产:
Request received:
{"a":"b"}
-------------
{}
==============
还有一点html+js来说明问题:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<body>
<button type="button" onclick="doPost()">
POST
</button>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
function doPost() {
$.post("http://localhost:8080/x",
JSON.stringify({"a":"b"} ),
function(data) {});
}
</script>
</body>
</html>
生产:
Request received:
--------------
{{"a":"b"}=[Ljava.lang.String;@7a2897ac}
==============
因此,如果我将 $post 与字符串化的 json 字符串和回调一起使用,我会将所有内容都填充到单个参数键中。如果这是正常的,我想知道为什么,以及我应该如何在服务器上干净地解开这个问题。如果它不正常,我想知道我应该怎么做才能使用 $post 在响应正文中获取它。
更新:现在有一个feature request for jquery to support contentType on $.post
【问题讨论】: