javascript - 使用 Play Framework 以 JSON 格式提交表单

标签 javascript jquery json forms playframework

我正在尝试将表单作为 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>
} }

Controller 代码:

// 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)和基于 serializeObjectformAsJson() 函数轻松完成此操作功能。

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

关于javascript - 使用 Play Framework 以 JSON 格式提交表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29705494/

相关文章:

javascript - 如何使用 jQuery 获取没有边框的元素对象?

android - 用gson反序列化json

javascript - JS toggleClass 正确的方式

javascript - 使用 JavaScript 解析 URL

javascript - Highcharts 加载数据而不是绘图

asp.net - 来自 javascript PageMethods 的自定义 C# 数据传输对象

json - REACT - 如何显示 url 中包含的文本

Javascript FileReader 存储到内存中 - 参数 1 的类型不是 'Blob'

c# - 如何在点击asp.net按钮时自动点击html按钮

javascript - 如何停止一次后发生的事件