假设有这样一个form
<div id="myform" data-dojo-type="dijit/form/Form"> <div>姓名<input name="name" data-dojo-type="dijit/form/TextBox" /></div> <div>年龄<input name="age" data-dojo-type="dijit/form/TextBox" /></div> <div>办公电话<input name="phone.company" data-dojo-type="dijit/form/TextBox" /></div> <div>家庭电话<input name="phone.home" data-dojo-type="dijit/form/TextBox" /></div> <div>个人电话<input name="phone.private" data-dojo-type="dijit/form/TextBox" /></div> <button id='btn' data-dojo-type="dijit/form/Button" onclick="submit()">提交</button> </div>我们希望提交时把整个form表单转换为json,同时phone转换为json的内部对象,就是这种格式
{"name":"陈","age":"24","phone":{"company":"123","home":"456","private":"789"}}这样通过rest方式,可以直接映射json到vo对象中
public class Persion{ private String name; private String age; private Map phone = new HashMap(); }json到vo的映射是后台部分。页面dojo实现form到json的转换是这样的:
require(["dojo/request/xhr","dojo/dom-form","dojo/json"],function(xhr,domForm,JSON) { var val = JSON.stringify(dijit.byId("myform").get('value')); // form到json转换 xhr.post("url",{ headers: { 'Content-Type': 'application/json; charset=UTF-8' },handleAs: "json",data: val // json }).then(function(data) { // sucess },function(err) { // fail }); });
需要注意的是,必须用JSON.stringify(dijit.byId("myform").get('value'))这种方式才能转换成想要的json格式。domForm.toJson("myform")或者JSON.stringify(domForm.toObject("myform"))转换出来都是这种结果
{"name":"陈","phone.company":"123","phone.home":"456","phone.private":"789"}}原文链接:https://www.f2er.com/dojo/291185.html