form 转json,将form表单中的数据序列化数组后转换为Json【改】
改成本地方法:
//表单序列化为json对象
function form2o(formId)
{
var o = {};
var a = $(formId).serializeArray();
$.each(a, function() {
if (o[this.name]) {
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;
};
转
form 转json,将form表单中的数据序列化数组后转换为Json
页面中引用了jquery,第一想到的就是序列化,但是序列化后的表单字段为a=1&b=2这种。
这里写一个jquery的扩展方法
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
$.fn.serializeObject = function() { var o = {}; var a = this.serializeArray(); $.each(a, function() { if (o[this.name]) { 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; }; |
这个方法是将表单序列化成json的。
像这样调用:
|
1
2
|
var para = $('form').serializeObject() ; para = JSON.stringify(para) ; |
先把表单数据序列化为一个json对象,然后将json对象转换成一个json字符串。
这样para就是一个json字符串啦。就可以发起请求了
注意:这个只能获取到所有的input标签,如果想获取下拉框的话,需要单独获取,然后把获取到的值拼接进去。例如:
|
1
2
3
4
5
|
var data=$("#fm").serializeObject();JSON.stringify(data);data.txt2="1111";//修改值var sel1=$("#sel1").val();//获取下拉框的值data.sel1=sel1;//拼接进去 |
百闻不如一见,百见不如一做,只有做了,才知道问题出现在哪儿,才能去解决问题。

浙公网安备 33010602011771号