使用Play Framework以JSON形式提交表单 [英] Submit Form as JSON with Play Framework
问题描述
我试图将表单作为JSON对象提交,因为我想创建一个带有play的REST API.
I am trying to submit a form as a JSON object because I want to create a REST API with play.
我遇到的问题是Play告诉我这不是有效的JSON.
The issue that I have is that Play tells me that is not a valid JSON.
我的FORM代码:
@(form : Form[Product]) @main("Create Form"){
@helper.form(routes.Products.createProduct, 'enctype -> "application/json"){
@helper.inputText(form("name"))
<button>Commit</button>
} }
控制器代码:
// 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的表单语法来做到这一点.
Whats the best way to do this? a read about submitting with Ajax but because I am new with play I don´t figure it out the way to do this with Play´s form syntax.
推荐答案
您可以轻松地使用jQuery(确保您的头部包含jQuery)和基于
You can do it easily with jQuery (so make sure you have jQuery included in your head) and formAsJson()
function based on serializeObject
function.
@helper.form(routes.Products.createProduct(), 'id -> "myform") {
@helper.inputText(jsonForm("name"))
<button>Commit</button>
}
<script>
$.fn.formAsJson = function(){
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return JSON.stringify(o)
};
var $myform = $("#myform");
$myform.on('submit', function () {
$.ajax({
url: $myform.attr('action'),
type: $myform.attr('method'),
contentType: "application/json",
data: $myform.formAsJson(),
success:function(){
alert("Great! Everything's OK!");
},
error: function(){
alert("Booo, something wrong :(");
}
});
return false;
});
</script>
和您的createProduct()
操作可能类似于:
and your createProduct()
action could look just like:
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();
}
这篇关于使用Play Framework以JSON形式提交表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!