使用 Play Framework 以 JSON 形式提交表单

Submit Form as JSON with Play Framework

我正在尝试将表单作为 JSON 对象提交,因为我想创建一个 REST API with play。

我遇到的问题是 Play 告诉我这不是有效的 JSON。

我的表格代码:

@(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 的表单语法来做到这一点。

您可以使用 jQuery(因此请确保您的头脑中包含 jQuery)和基于 serializeObject 函数的 formAsJson() 函数轻松完成此操作。

@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() 操作可能看起来像:

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();
}