<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>Document</title>
<script src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<form id="myform">
<table>
<tr>
<td>姓名:</td>
<td> <input type="text" name="name" value="旺旺"/> </td>
</tr>
<tr>
<td>性别:</td>
<td>
<input type="radio" name="sex" value="男" checked> 男
<input type="radio" name="sex" value="女"> 女
</td>
</tr>
<tr>
<td>年龄:</td>
<td>
<select name="age">
<option value="10">10</option>
<option value="20" selected>20</option>
<option value="30">30</option>
</select>
</td>
</tr>
<tr>
<td>爱好:</td>
<td>
<input type="checkbox" value="read" name="hobby" checked>读书
<input type="checkbox" value="music" name="hobby" checked>音乐
<input type="checkbox" value="draw" name="hobby" checked>画画
<input type="checkbox" value="sport" name="hobby">运动
</td>
</tr>
<tr>
<td colspan="2">
<input type="button" id="submitBtn" value="提交" />
</td>
</tr>
</table>
</form>
<script>
/**序列化表单,多个value用数组存放**/
$.fn.serializeObject = function() {
var o = {};
var arr = this.serializeArray();
$.each(arr,function(){
if (o[this.name]) { //返回json中有该属性
if (!o[this.name].push) { //将已存在的属性值改成数组
o[this.name] = [ o[this.name] ];
}
o[this.name].push(this.value || ''); //将值存放到数组中
} else { //返回json中没有有该属性
o[this.name] = this.value || ''; //直接将属性和值放入返回json中
}
});
return o;
}
/**序列化表单,多个value用逗号隔开**/
$.fn.serializeObject2 = function() {
var o = {};
var arr = this.serializeArray();
$.each(arr,function(){
if (o[this.name]) { //返回json中有该属性
o[this.name]=o[this.name]+','+(this.value || '');//序列化表单,多个value用逗号隔开
} else { //返回json中没有有该属性
o[this.name] = this.value || ''; //直接将属性和值放入返回json中
}
});
return o;
}
/**初始化测试**/
$(function() {
$("#submitBtn").click(function() {
var params = $("#myform").serializeObject(); //将表单序列化为JSON对象
console.info(params);
var params2 = $("#myform").serializeObject2(); //将表单序列化为JSON对象
console.info(params2);
});
var json={'a':'a我的#+~','b':'b','c':'c'};
var jsonStr=JSON.stringify(json);//json转字符串
var json2=JSON.parse(jsonStr);//字符串转json
console.info(jsonStr);
console.info('encodeURI:\n'+encodeURI(jsonStr));//转码非url的字符
console.info('encodeURIComponent:\n'+encodeURIComponent(jsonStr));//转码所有的特殊字符
/*encodeURIComponent() 函数 与 encodeURI() 函数的区别之处,前者假定它的参数是 URI 的一部分(比如协议、主机名、路径或查询字符串)。因此 encodeURIComponent() 函数将转义用于分隔 URI 各个部分的标点符号。*/
console.info(json2);
})
</script>
</body>
</html>