【问题标题】:How to get the posted "id=1&id=2" in action, in play2?如何在 play2 中获取已发布的“id=1&id=2”?
【发布时间】:2012-04-16 13:41:04
【问题描述】:

我有一个包含一些行的表单,每行前面都有一个复选框。用户可以选择其中一些,然后按“删除选定的行”按钮提交。

发布的数据如下:

id=1&id=2&id=3

我想让它们发挥作用,我的代码是:

def delete = Action { implicit request =>
   Form("id"->seq(nonEmptyText)).bindFromRequest.fold(
      errors => BadRequest, 
      ids => {
         println(ids)    // (!)
         for(id<-ids) deleteRow(id)
      }
   )
}

但我发现 id 总是List(),一个空列表。

我检查了 play2 提供的“表单示例”,发现seq(...) 应该只适用于这种格式的发布数据:

company sdfdsf
firstname   sdfds
informations[0].email   sdf@sdf.com
informations[0].label   wef
informations[0].phones[0]   234234
informations[0].phones[1]   234234
informations[0].phones[x]   
informations[1].email   sdf@sdf.com
informations[1].label   wefwef
informations[1].phones[0]   234234
informations[1].phones[x]   
informations[x].email   
informations[x].label   
informations[x].phones[x]   

请注意参数名称中有很多[0]或其他索引。

【问题讨论】:

    标签: scala http-post playframework-2.0


    【解决方案1】:

    在这种情况下,您可以(并且可能想要)访问请求正文的 url 编码内容,而不是使用 Form 帮助程序。

    这样做的方法是例如:

    def delete = Action { implicit request =>
      request.body.asFormUrlEncoded match {
        case Some(b) =>
          val ids = b.get("id")
          for(id <- ids) deleteRow(id)
          Ok
        case None =>
          BadRequest
      }
    }
    

    【讨论】:

      【解决方案2】:

      目前在 Play2 中这是一个硬限制。

      整个表单绑定框架基于从/到 Map[String,String] 的转换,对于 FormUrlEncoded 和 Json 输入,这是通过丢弃除每个键的第一个值之外的所有内容来完成的。

      我正在尝试将所有内容更改为 Map[String,Seq[String]],但目前尚不清楚该方法的兼容性如何。有关正在进行的工作,请参阅https://github.com/bartschuller/Play20/tree/formbinding(分支将在没有警告的情况下被强制推送)。

      欢迎批评、API 建议和测试。

      【讨论】:

        【解决方案3】:

        如果你让你发布的数据看起来像

        id[0]=1&id[1]=2&id[2]=3
        

        它应该可以工作。

        【讨论】:

          猜你喜欢
          • 2013-05-10
          • 2015-05-05
          • 1970-01-01
          • 2019-10-26
          • 1970-01-01
          • 2018-06-07
          • 2014-11-11
          • 1970-01-01
          相关资源
          最近更新 更多