我在序列化表单时遇到了一些问题
<form>
<input type="text" name="name1" value="value1"/>
<input type="text" name="name2" value="value2"/>
</form>
$(form).serializeArray()将返回[{name:"name1",value:"value1"},{name:"name2",value:"value2"}]对。
是否可以在表单中获得输出
{name1:value1,name2:value2}这样它们就更容易处理了?
发布于 2012-07-07 23:24:05
var result = { };
$.each($('form').serializeArray(), function() {
result[this.name] = this.value;
});
// at this stage the result object will look as expected so you could use it
alert('name1 = ' + result.name1 + ', name2 = ' + result.name2);Live demo.
发布于 2015-08-01 00:54:43
$.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;
};发布于 2012-09-13 11:42:59
如果您的表单没有复选框或单选按钮,接受的答案效果很好。由于这些组都具有相同的name属性,因此需要在对象内创建一个数组值。所以对于像这样的html:
<input type="checkbox" value="1" name="the-checkbox">
<input type="checkbox" value="2" name="the-checkbox">
<input type="checkbox" value="3" name="the-checkbox">你会得到:
{the-checkbox:['1', '2', '3']}一小段This代码可以很好地处理所有事情。
/*!
* jQuery serializeObject - v0.2 - 1/20/2010
* http://benalman.com/projects/jquery-misc-plugins/
*
* Copyright (c) 2010 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*/
// Whereas .serializeArray() serializes a form into an array, .serializeObject()
// serializes a form into an (arguably more useful) object.
(function($,undefined){
'$:nomunge'; // Used by YUI compressor.
$.fn.serializeObject = function(){
var obj = {};
$.each( this.serializeArray(), function(i,o){
var n = o.name,
v = o.value;
obj[n] = obj[n] === undefined ? v
: $.isArray( obj[n] ) ? obj[n].concat( v )
: [ obj[n], v ];
});
return obj;
};
})(jQuery);用法
$(form).serializeObject();https://stackoverflow.com/questions/11376184
复制相似问题