一.数据表单
二.将整个表单中的数据封装成json格式
function saveOrUpdate(){
//返回json数组
var formData = $('#messagePrioritySetting').serializeArray();
// 获得json表单的对象 此方法在IE中不支持
var jsonObject = $('#messagePrioritySetting').serializeJSON();
// 把json对象转成字符串
var jsonString = JSON.stringify(jsonObject)
var tableData={"menu":[ ]};
var arr = $("table tr");
for(var i = 1; i < arr.length; i ++){
var id = $(arr[i]).find('td').eq(0).children("[type='hidden']").val();
var messageTypeValue = $(arr[i]).find('td').eq(1).text();
var priorityLevel = $(arr[i]).find('td').eq(2).text();
var expandStatus = $(arr[i]).find('td').eq(3).find
("select option:checked").text();
var expandStatusNum = "";
if($.trim(expandStatus) === "是"){
expandStatus = "0";
}else{
expandStatus = "1";
}
// 获得字符串去掉空格
$.trim(id);
$.trim(messageTypeValue);
$.trim(priorityLevel);
$.trim(expandStatus);
// 封装成json格式,一个json对象,就是表格中一条数据
var aMenu={
"id":id,
"messageTypeValue":messageTypeValue,
"priorityLevel":priorityLevel,
"expandStatus":expandStatus
};
tableData.menu.push(aMenu);
}
/*
{"menu":[{"id":"12dds","messageTypeValue":"NNQ信息 ","expandStatus":"1"},
{"id":"sad11","messageTypeValue":"LSQ信息 ","expandStatus":"0"}
]}
*/
// 转成字符串
var submitData = JSON.stringify(tableData);
$.ajax({
url:"${pageContext.request.contextPath }/messageAction_
messageSettingAll.action",
type:"POST",
data:submitData,
contentType:"application/json", //缺失会出现URL编码,无法转成json对象
success: function (result) {
alert("设置成功!");
},
error: function () {
alert("设置失败!");
}
});
}
三.后台对前端传递的json数据进行接收
public void messageSettingAll() throws IOException{
String mpsStr = getRequestPostData(request);
// 转化为json对象
JSONObject mpsObject = JSONObject.parseObject(mpsStr);
// 通过key获取value
String jsonString = mpsObject.getString("menu");
// 转化为实体类对象
List messagePushSettingList = JSON.parseArray(jsonString,
MessagePushSetting.class);
}
//解析请求的Json数据
private String getRequestPostData(HttpServletRequest request) throws IOException {
int contentLength = request.getContentLength();
if(contentLength<0){
return null;
}
byte buffer[] = new byte[contentLength];
for (int i = 0; i < contentLength;) {
int len = request.getInputStream().read(buffer, i, contentLength - i);
if (len == -1) {
break;
}
i += len;
}
return new String(buffer, "utf-8");
}