json封装代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function getFormJson(frm) { //frm:form表单的id
var o = {};
var a = $("#"+frm).serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
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格式,ajax使用如下:

1
2
3
4
5
6
7
8
$.ajax({
type: 'post',
url: 'your url',
data: getFormJson(frm),
success: function(data) {
// your code
}
});