使用Play Framework以JSONforms提交表单
我试图将表单作为JSON对象提交,因为我想创建一个带有play的REST API。
我遇到的问题是Play告诉我这不是一个有效的JSON。
我的FORM代码:
@(form : Form[Product]) @main("Create Form"){ @helper.form(routes.Products.createProduct, 'enctype -> "application/json"){ @helper.inputText(form("name")) } }
控制器代码:
// Read JSON an tell if it has a name Path @BodyParser.Of(BodyParser.TolerantJson.class) public static Result createProduct() { JsonNode json = request().body().asJson(); String name = json.findPath("name").textValue(); if (name == null) { return badRequest("Not JSON"); } else { return ok(name); } }
什么是最好的方法呢? 阅读有关使用Ajax提交的内容,但因为我是Play的新手,所以我不想用Play的表单语法来解决这个问题。
您可以使用jQuery轻松完成(因此请确保您的头部包含jQuery)和基于serializeObject
函数的formAsJson()
函数。
@helper.form(routes.Products.createProduct(), 'id -> "myform") { @helper.inputText(jsonForm("name")) }
并且您的createProduct()
操作可能看起来像:
public static Result createProduct() { JsonNode json = request().body().asJson(); String name = json.findPath("name").textValue(); if (json==null || name==null || ("").equals(name.trim())){ return badRequest(); } return ok(); }