-->

从PlayFramework形式张贴JSON-数据(Post JSON-Data from Play

2019-10-22 14:13发布

玩框架提供了一种经由访问请求体JSON-数据request().body().asJson() 使用表单助手不张贴在JSON格式的数据。

那么,什么是最好的方式,在游戏的应用程序,将它传递给控制器之前 ,表单数据的JSON对象转换?

提前致谢。

Answer 1:

当您检索请求的有效载荷数据,你可以使用BodyParsers (他们使用Content-Type头解析有效载荷送入别的东西),或者你可以通过表单自己得到了有效载荷的结合,或直接作为JSON, 如果你有一个JSON /文本有效载荷请求主体。

你的情况,你有一个Content-Type任一application/x-www-form-urlencoded OR multipart/form-data 。 所以,你需要绑定到形式与助手类获得这些数据,如果你真的想将其转换成JSON你只添加在ObjectNode插入它的额外步骤。

如果你希望你的表单数据,JSON,直接进行转换的前端,如果可能的话,并在身体把它作为Content-Type application/json

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



Answer 2:

1.Serialize形式的JSON对象

$.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与内容类型AJAX请求application/json

$.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;
});
});


文章来源: Post JSON-Data from PlayFramework form