将Jquery序列化后的表单值转换成Json

通过$("#form").serialize()可以获取到序列化的表单值字符串:

a=1&b=2&c=3&d=4&e=5

通过$("#form").serializeArray()输出以数组形式序列化表单值:

[ 
  {name: 'firstname', value: 'Hello'}, 
  {name: 'lastname', value: 'World'},
  {name: 'alias'}, // 值为空
]

重写:

$.fn.serializeObject = function()
{
	var o = {};
	var a = this.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;
};

 通过 $("#form").serializeObject(); 就可以得到Js object内容:

 
 {name: 'value', name1: 'value1'}

以json传递后台

JSON.stringify(obj)

猜你喜欢

转载自blog.csdn.net/ding_xc/article/details/81875675