Post JSON-来自 PlayFramework 表单的数据

Post JSON-Data from PlayFramework form

Play Framework 提供了一种通过 request().body().asJson() 访问请求正文中的 JSON 数据的方法。使用表单助手不会 post JSON 格式的数据。

那么,在播放应用程序中,将表单数据转换为 json 对象的最佳方法是什么 将其传递给控制器​​之前?

提前致谢。

当您检索请求负载数据时,您可以使用 BodyParsers(他们使用 Content-Type header 将负载解析为其他内容)或者您可以通过以下方式自行获取负载表单绑定或直接作为 JSON IF 你在请求 body 中有一个 JSON/textual 负载。

在你的情况下,你有 Content-Type application/x-www-form-urlencoded multipart/form-data .所以你需要用一个助手绑定到那个表单 class 获取数据,如果你真的想把它转换成 JSON 你只需添加一个额外的步骤将它插入到 ObjectNode 中。

如果您希望表单数据为 JSON,请在可能的情况下直接在前端进行转换,然后在 body 中将其作为 Content-Type application/json 发送。

现在,你明白为什么你想做的只是增加额外的复杂性而没有明显的收获吗?

1.Serialize 表单到 JSON-Object

$.fn.serializeObject = 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 o;
};

2.Define 内容类型为 application/json

的 AJAX 请求
$.ajaxSetup({
    contentType: "application/json; charset=utf-8" 
});

function request(path, params, method) {
method = method || "POST";

$.ajax({
    url: path,
    type: method,
    data: params,
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function (result) {
        //do something
    },
    error: function (xhr, ajaxOptions, thrownError) {
        //do something
    }
});
}

3.Send 表单提交后的数据

$(function() {
var url = "/api/route";

$('form').submit(function() {
    var json = JSON.stringify($('form').serializeObject());
    request(url, json);
    return false;
});
});