如何将表单的所有元素转换为JavaScript对象?
我希望有某种方法从表单自动构建JavaScript对象,而不必遍历每个元素。我不希望使用$('#formid').serialize();返回的字符串;,我也不希望$('#formid').serializeArray()返回映射;
如何将表单的所有元素转换为JavaScript对象?
我希望有某种方法从表单自动构建JavaScript对象,而不必遍历每个元素。我不希望使用$('#formid').serialize();返回的字符串;,我也不希望$('#formid').serializeArray()返回映射;
当前回答
这是对Tobias Cohen函数的改进,该函数在多维数组中运行良好:
http://jsfiddle.net/BNnwF/2/
然而,这不是一个jQuery插件,但如果您想这样使用它,只需几秒钟就可以将它变成一个:只需替换函数声明包装器:
function serializeFormObject(form)
{
...
}
具有:
$.fn.serializeFormObject = function()
{
var form = this;
...
};
我想这与梅斯克的解决方案相似,因为它做了相同的事情,但我认为这有点干净和简单。我还将macek的测试用例输入添加到小提琴中,并添加了一些额外的输入。到目前为止,这对我来说很好。
function serializeFormObject(form)
{
function trim(str)
{
return str.replace(/^\s+|\s+$/g,"");
}
var o = {};
var a = $(form).serializeArray();
$.each(a, function() {
var nameParts = this.name.split('[');
if (nameParts.length == 1) {
// New value is not an array - so we simply add the new
// value to the result object
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 || '';
}
}
else {
// New value is an array - we need to merge it into the
// existing result object
$.each(nameParts, function (index) {
nameParts[index] = this.replace(/\]$/, '');
});
// This $.each merges the new value in, part by part
var arrItem = this;
var temp = o;
$.each(nameParts, function (index) {
var next;
var nextNamePart;
if (index >= nameParts.length - 1)
next = arrItem.value || '';
else {
nextNamePart = nameParts[index + 1];
if (trim(this) != '' && temp[this] !== undefined)
next = temp[this];
else {
if (trim(nextNamePart) == '')
next = [];
else
next = {};
}
}
if (trim(this) == '') {
temp.push(next);
} else
temp[this] = next;
temp = next;
});
}
});
return o;
}
其他回答
使用maček的解决方案,我对其进行了修改,使其与ASP.NET MVC在同一表单上处理嵌套/复杂对象的方式一致。您所要做的就是将验证部分修改为:
"validate": /^[a-zA-Z][a-zA-Z0-9_]*((?:\[(?:\d*|[a-zA-Z0-9_]+)\])*(?:\.)[a-zA-Z][a-zA-Z0-9_]*)*$/,
这将匹配并正确映射具有以下名称的元素:
<input type="text" name="zooName" />
And
<input type="text" name="zooAnimals[0].name" />
在不检查每个元素的情况下,确实无法做到这一点。您真正想知道的是“是否有其他人已经编写了一个将表单转换为JSON对象的方法?”类似于下面的内容应该可以工作——请注意,它只会为您提供通过POST返回的表单元素(必须有名称)。这是未测试的。
function formToJSON( selector )
{
var form = {};
$(selector).find(':input[name]:enabled').each( function() {
var self = $(this);
var name = self.attr('name');
if (form[name]) {
form[name] = form[name] + ',' + self.val();
}
else {
form[name] = self.val();
}
});
return form;
}
从一些旧的答案来看:
$('form input, form select').toArray().reduce(function(m,e){m[e.name] = $(e).val(); return m;},{})
对于这个问题,我找到的最简单、最准确的方法是使用bbq插件或这个插件(大约0.5K字节大小)。
它也适用于多维阵列。
$.fn.serializeObject=函数(){return$.departam(this.serialize());};
此函数返回转换为正确类型的所有值;
bool/string/(integer/floats)可能
虽然您需要jQuery来实现这一点,但由于serializeArray也是jQuery,所以没什么大不了的。
/**
* serialized a form to a json object
*
* @usage: $("#myform").jsonSerialize();
*
*/
(function($) {
"use strict";
$.fn.jsonSerialize = function() {
var json = {};
var array = $(this).serializeArray();
$.each(array, function(key, obj) {
var value = (obj.value == "") ? false : obj.value;
if(value) {
// check if we have a number
var isNum = /^\d+$/.test(value);
if(isNum) value = parseFloat(value);
// check if we have a boolean
var isBool = /^(false|true)+$/.test(value);
if(isBool) value = (value!=="false");
}
json[obj.name] = value;
});
return json;
}
})(jQuery);