从PlayFramework表单发布JSON数据 [英] Post JSON-Data from PlayFramework form
本文介绍了从PlayFramework表单发布JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Play Framework提供了一种通过request().body().asJson()
访问请求正文中的JSON-Data的方法.使用表单帮助程序不会以JSON格式发布数据.
Play Framework provides a way to access JSON-Data in a request-body via request().body().asJson()
. Using form-helpers does not post data in JSON-format.
那么,在播放应用程序中,在将表单数据传递给控制器之前,将表单数据转换为json对象的最佳方法是什么?
So, what is the best way, in a play-application, to convert the form-data to a json-object before passing it to the controller?
谢谢.
推荐答案
1.将表单序列化为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.定义内容类型为application/json
2.Define an AJAX request with content type 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.提交表单后发送数据
$(function() {
var url = "/api/route";
$('form').submit(function() {
var json = JSON.stringify($('form').serializeObject());
request(url, json);
return false;
});
});
这篇关于从PlayFramework表单发布JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文