如何将表单的所有元素转换为JavaScript对象?
我希望有某种方法从表单自动构建JavaScript对象,而不必遍历每个元素。我不希望使用$('#formid').serialize();返回的字符串;,我也不希望$('#formid').serializeArray()返回映射;
如何将表单的所有元素转换为JavaScript对象?
我希望有某种方法从表单自动构建JavaScript对象,而不必遍历每个元素。我不希望使用$('#formid').serialize();返回的字符串;,我也不希望$('#formid').serializeArray()返回映射;
当前回答
我喜欢塞缪尔的版本,但我相信它有一个小错误。通常JSON发送为
{“coreSKU”:“PCGUYJS”,“name_de”:“whatever”,。。。
不作为
〔{“coreSKU”:“PCGUYJS”},{“name_de”:“whatever”},。。。
因此,功能IMO应为:
App.toJson = function( selector ) {
var o = {};
$.map( $( selector ), function( n,i )
{
o[n.name] = $(n).val();
});
return o;
}
并将其包装在数据数组中(正如通常预期的那样),最后将其作为跨页发送App.stringify({data:App.toJson(“#cropform:input”)})
对于精简版本,请参见问题3593046,对于所有可能的版本,请参阅json2.js。这应该涵盖了所有内容:)
其他回答
我的库phery中的代码有一个序列化例程,可以处理非常复杂的表单(如演示中所示https://github.com/pocesar/phery/blob/master/demo.php#L1664),而且不是一刀切。它实际上检查每个字段的类型。例如,单选框与范围不同,与keygen不同,与select multiple不同。我的功能涵盖了这一切,你可以看到它在https://github.com/pocesar/phery/blob/master/phery.js#L1851.
serializeForm:function (opt) {
opt = $.extend({}, opt);
if (typeof opt['disabled'] === 'undefined' || opt['disabled'] === null) {
opt['disabled'] = false;
}
if (typeof opt['all'] === 'undefined' || opt['all'] === null) {
opt['all'] = false;
}
if (typeof opt['empty'] === 'undefined' || opt['empty'] === null) {
opt['empty'] = true;
}
var
$form = $(this),
result = {},
formValues =
$form
.find('input,textarea,select,keygen')
.filter(function () {
var ret = true;
if (!opt['disabled']) {
ret = !this.disabled;
}
return ret && $.trim(this.name);
})
.map(function () {
var
$this = $(this),
radios,
options,
value = null;
if ($this.is('[type="radio"]') || $this.is('[type="checkbox"]')) {
if ($this.is('[type="radio"]')) {
radios = $form.find('[type="radio"][name="' + this.name + '"]');
if (radios.filter('[checked]').size()) {
value = radios.filter('[checked]').val();
}
} else if ($this.prop('checked')) {
value = $this.is('[value]') ? $this.val() : 1;
}
} else if ($this.is('select')) {
options = $this.find('option').filter(':selected');
if ($this.prop('multiple')) {
value = options.map(function () {
return this.value || this.innerHTML;
}).get();
} else {
value = options.val();
}
} else {
value = $this.val();
}
return {
'name':this.name || null,
'value':value
};
}).get();
if (formValues) {
var
i,
value,
name,
$matches,
len,
offset,
j,
fields;
for (i = 0; i < formValues.length; i++) {
name = formValues[i].name;
value = formValues[i].value;
if (!opt['all']) {
if (value === null) {
continue;
}
} else {
if (value === null) {
value = '';
}
}
if (value === '' && !opt['empty']) {
continue;
}
if (!name) {
continue;
}
$matches = name.split(/\[/);
len = $matches.length;
for (j = 1; j < len; j++) {
$matches[j] = $matches[j].replace(/\]/g, '');
}
fields = [];
for (j = 0; j < len; j++) {
if ($matches[j] || j < len - 1) {
fields.push($matches[j].replace("'", ''));
}
}
if ($matches[len - 1] === '') {
offset = assign_object(result, fields, [], true, false, false);
if (value.constructor === Array) {
offset[0][offset[1]].concat(value);
} else {
offset[0][offset[1]].push(value);
}
} else {
assign_object(result, fields, value);
}
}
}
return result;
}
它是我的库phery的一部分,但可以移植到您自己的项目中。它在应该有数组的地方创建数组,从select、normalize复选框等选项中获取正确的选择选项。如果要将其转换为JSON(真正的JSON字符串),只需执行JSON.stringify($('form').serializeForm());
Use:
function form_to_json (selector) {
var ary = $(selector).serializeArray();
var obj = {};
for (var a = 0; a < ary.length; a++) obj[ary[a].name] = ary[a].value;
return obj;
}
输出:
{"myfield": "myfield value", "passwordfield": "mypasswordvalue"}
如果您想将表单转换为javascript对象,那么最简单的解决方案(此时)是使用jQuery的each和serializArray函数方法。
$.fn.serializeObject = function() {
var form = {};
$.each($(this).serializeArray(), function (i, field) {
form[field.name] = field.value || "";
});
return form;
};
GitHub上托管的插件:https://github.com/tfmontague/form-object/blob/master/README.md
可与Bower一起安装:船首装置git://github.com/tfmontague/form-object.git
使用lodash#set
let serialized = [
{ key: 'data[model][id]', value: 1 },
{ key: 'data[model][name]', value: 'product' },
{ key: 'sid', value: 'dh0un1hr4d' }
];
serialized.reduce(function(res, item) {
_.set(res, item.key, item.value);
return res;
}, {});
// returns
{
"data": {
"model": {
"id": 1,
"name": "product"
}
},
"sid": "dh0un1hr4d"
}
要获得快速、现代的解决方案,请使用JSONify jQuery插件。下面的示例是从GitHub README中逐字摘录的。这一切都归功于插件作者Kushal Pandya。
鉴于:
<form id="myform">
<label>Name:</label>
<input type="text" name="name"/>
<label>Email</label>
<input type="text" name="email"/>
<label>Password</label>
<input type="password" name="password"/>
</form>
正在运行:
$('#myform').jsonify();
生产:
{"name":"Joe User","email":"joe@example.com","password":"mypass"}
如果要使用此JSON对象执行jQuery POST:
$('#mybutton').click(function() {
$.post('/api/user', JSON.stringify($('#myform').jsonify()));
}