如果您的表单没有复选框或单选按钮,则接受的答案非常有用。由于这些组都具有相同的名称属性,因此您需要在对象内创建一个数组值。所以对于像这样的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']}
这段代码可以很好地处理所有事情。
/*!
* 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();