【问题标题】:Submit Form as JSON with Play Framework使用 Play 框架以 JSON 格式提交表单
【发布时间】:2015-06-24 16:13:47
【问题描述】:

我正在尝试将表单作为 JSON 对象提交,因为我想创建一个带有播放功能的 REST API。

我遇到的问题是 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 的表单语法来做到这一点。

【问题讨论】:

    标签: javascript jquery json forms playframework


    【解决方案1】:

    您可以使用 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();
    }
    

    【讨论】:

    • 感谢您的回复,为我工作。但我认为我们可以识别请求类型,因为 Play Framework 有一个 MimeType 类。你知道如何在 java 中创建一个 switch 子句来告诉 Play ok 如果 MimeType.Json 执行此操作,如果 MimeType.HTML 执行另一个操作?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-10
    • 2013-07-24
    • 1970-01-01
    • 2011-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多