表单序列化为Json(只限input)
转载自:http://blog.csdn.net/itmyhome1990/article/details/42099885
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="/WEB-INF/jsp/common.jsp"%>
<!DOCTYPE html >
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<script type="text/javascript" src="${basePath}/system/lib/jquery-1.11.3/jquery.min.js"></script>
<script type="text/javascript" language="JavaScript">
(function($){
$.fn.serializeJson = function(){
var jsonData1 = {};//声明一个空map
var serializeArray = this.serializeArray();
// 先转换成{"id": ["12","14"], "name": ["aaa","bbb"], "pwd":["pwd1","pwd2"]}这种形式
$(serializeArray).each(function () {
if (jsonData1[this.name]) {//如果map有id\name\pwd键
if ($.isArray(jsonData1[this.name])) {//如果key对应value是数组
jsonData1[this.name].push(this.value);
} else {
jsonData1[this.name] = [jsonData1[this.name], this.value];//将key对应value设为数组
}
} else {
jsonData1[this.name] = this.value;
}
});
// 再转成[{"id": "12", "name": "aaa", "pwd":"pwd1"},{"id": "14", "name": "bb", "pwd":"pwd2"}]的形式
var vCount = 0;
// 计算json内部的数组最大长度
for(var item in jsonData1){
var tmp = $.isArray(jsonData1[item]) ? jsonData1[item].length : 1;
vCount = (tmp > vCount) ? tmp : vCount;
}
if(vCount > 1) {
var jsonData2 = new Array();
for(var i = 0; i < vCount; i++){
var jsonObj = {};
for(var item in jsonData1) {
jsonObj[item] = jsonData1[item][i];
}
jsonData2.push(jsonObj);
}
return JSON.stringify(jsonData2);
}else{
return "[" + JSON.stringify(jsonData1) + "]";
}
};
})(jQuery);
function submitUserList_4() {alert("ok");
var jsonStr = $("#form1").serializeJson();
console.log("jsonStr:\r\n" + jsonStr);
/* $.ajax({
url: "/user/submitUserList_4",
type: "POST",
contentType : 'application/json;charset=utf-8', //设置请求头信息
dataType:"json",
data: jsonStr,
success: function(data){
alert(data);
},
error: function(res){
alert(res.responseText);
}
}); */
}
</script>
</head>
<body>
<h1>submitUserList_4</h1>
<form id="form1">
ID:<input type="text" name="id"><br/>
Username:<input type="text" name="name"><br/>
Password:<input type="text" name="pwd"><br/><br/>
ID:<input type="text" name="id"><br/>
Username:<input type="text" name="name"><br/>
Password:<input type="text" name="pwd"><br/><br/>
<input type="button" value="submit" onclick="submitUserList_4()">
</form>
</body>