【问题标题】:ajax json playframwork parser can not get correspond valueajax json playframework解析器无法获取对应值
【发布时间】:2014-07-13 17:01:44
【问题描述】:

我的框架是 playframework2.2.2。 我使用 jquery 发送 ajax json: 我的 javascript(客户端)部分:

$("#newapply" ).click(function(){
  var htmlrespone=$.ajax({
    type : 'post',
    url : ' @routes.CommonController.postdata ',
    data : JSON.stringify({"userid": "111233456"}),
    sucess:function(){
      $("#newapply" ).html("already apply");
      $("#newapply" ).prop("enable",false);
    },
    contentType: 'appliction/json'
  });
})

我的萤火虫的帖子字符串是:

{"userid":"111233456"}

我的服务器部分收到的帖子是:

def postdata = Action { request =>
  val body: AnyContent = request.body
  val textBody: Option[JsValue] = body.asJson   //here I always get None I donot know why
  textBody.map{json=>
    Ok("Got:"+(json\"userid").as[String])
  }.getOrElse{
    BadRequest("Expecting text/plain request body")
  }
}

这里我总是得到 BadRequest,因为 getOrElse 语句总是 None。 我认为帖子应该是 json 对象或 JsValue。 但为什么我在这里没有?如何从 body 中获取 JsValue?

【问题讨论】:

    标签: ajax json scala playframework-2.0 playframework-2.2


    【解决方案1】:

    我认为,你不能简单地在 ajax 数据中传递请求正文数据。

    在 ajax 数据中,只需传递带有值的变量,像这样

    var reqData=JSON.stringify({"userid": "111233456"})
    $.ajax({
        type : 'post',
        url : ' @routes.CommonController.postdata() ', //add proper function brackets after postdata
        data : {"data",reqData},
        sucess:function(){
          $("#newapply" ).html("already apply");
          $("#newapply" ).prop("enable",false);
        }
      });
    

    (对不起,我只知道java不知道scala)

    在路由文件中,像这样添加

     controllers.CommonController.postdata(data: String ?="") 
    

    在你的控制器中,就这样做

     public static Result postdata (String data) {
      //do your stuff
        }
    

    希望这会有所帮助。

    【讨论】:

    • 对不起,我想传递json格式的数据,你的答案就是传递 application/form-url-encoded: Map[String, Seq[String]] 格式的数据。并且正文作为表单而不是真正的 json 接收。
    • 没关系。只需将 json 数据作为字符串传递并在控制器中,获取字符串并将其解析为 json。我希望,你知道如何将 json 字符串解析为 json 对象。
    【解决方案2】:

    您的应用程序/json 拼写错误。拥有 contentType: 'application/json' 字段应该是发送 json 请求所需的全部内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-07
      • 2016-12-14
      • 1970-01-01
      • 1970-01-01
      • 2015-03-15
      相关资源
      最近更新 更多