【问题标题】:Why does jquery post json as a parameter name instead of as the request body?为什么 jquery 将 json 作为参数名称而不是请求正文发布?
【发布时间】: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

【问题讨论】:

    标签: jquery json rest scalatra


    【解决方案1】:

    如果你下拉到$.ajax,我认为你可以做到这一点

    $.ajax(
      {
         url: "http://localhost:8080/x",
         data: JSON.stringify({a: 'b'}),
         processData: false,
         type: 'POST',
         contentType: 'application/json'
      }
    );
    

    processData 告诉 jquery 不要乱用你的数据,设置contentType 应该确保你的后端不会尝试解析 json,因为它是一个常规的 url 编码形式。

    【讨论】:

      【解决方案2】:

      您没有设置导致 $.post() 方法将其设置为 application/x-www-form-urlencoded 的内容类型。

      使用 $.ajax() 并将内容类型显式设置为 application/json。

      问候,文森特。

      【讨论】:

        【解决方案3】:

        Vincent Partington 是对的,默认 contentType 设置为 application/x-www-form-urlencoded

        直接使用 jQuery.ajax 函数或创建自己的简写。

        您也可以更改服务器端,请参阅 Spring 3 MVC - Advanced Data Binding - Form Request with List of Simple Objects 例如。但我只会使用完整的 ajax 函数。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-11-27
          • 2012-07-18
          • 1970-01-01
          • 1970-01-01
          • 2018-03-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多