如何将表单的所有元素转换为JavaScript对象?
我希望有某种方法从表单自动构建JavaScript对象,而不必遍历每个元素。我不希望使用$('#formid').serialize();返回的字符串;,我也不希望$('#formid').serializeArray()返回映射;
如何将表单的所有元素转换为JavaScript对象?
我希望有某种方法从表单自动构建JavaScript对象,而不必遍历每个元素。我不希望使用$('#formid').serialize();返回的字符串;,我也不希望$('#formid').serializeArray()返回映射;
当前回答
jQuery中有一个插件jQuery.serializeJSON。我已经在几个项目中成功地使用了它。它就像一个符咒。
其他回答
对于语义ui/formantic ui,有一个内置的行为get值:
const fields = $("#myForm.ui.form").form('get values');
const jsonStr = JSON.stringify(fields);
看见https://fomantic-ui.com/behaviors/form.html#/settings
get-values(标识符)返回与标识符数组匹配的元素值的对象。如果未通过IDS,将返回所有字段
此线程似乎已成为表单序列化的常见问题解答:)
我对PHP命名的看法:<input name=“user[name]”>
$('form').on('submit', function(ev) {
ev.preventDefault();
var obj = $(this).serializePHPObject();
// $.post('./', obj);
});
(function ($) {
// based on https://stackoverflow.com/a/25239999/1644202
// <input name="user[name]" >
$.fn.serializePHPObject = function () {
var obj = {};
$.each(this.serializeArray(), function (i, pair) {
var cObj = obj,
pObj,
cpName;
$.each(pair.name.split("["), function (i, pName) {
pName = pName.replace("]", "");
pObj = cObj;
cpName = pName;
cObj = cObj[pName] ? cObj[pName] : (cObj[pName] = {});
});
pObj[cpName] = pair.value;
});
return obj;
};
})(jQuery);
Tobias Cohen解决方案的固定版本。此函数正确处理0和“”等错误值。
jQuery.fn.serializeObject = function() {
var arrayData, objectData;
arrayData = this.serializeArray();
objectData = {};
$.each(arrayData, function() {
var value;
if (this.value != null) {
value = this.value;
} else {
value = '';
}
if (objectData[this.name] != null) {
if (!objectData[this.name].push) {
objectData[this.name] = [objectData[this.name]];
}
objectData[this.name].push(value);
} else {
objectData[this.name] = value;
}
});
return objectData;
};
以及一个CoffeeScript版本,方便您编写代码:
jQuery.fn.serializeObject = ->
arrayData = @serializeArray()
objectData = {}
$.each arrayData, ->
if @value?
value = @value
else
value = ''
if objectData[@name]?
unless objectData[@name].push
objectData[@name] = [objectData[@name]]
objectData[@name].push value
else
objectData[@name] = value
return objectData
【2020年更新】
在vanilla js中有一个简单的oneliner,它利用了fromEntries(一如既往,请检查浏览器支持):
Object.fromEntries(new FormData(form))
如果要发送带有JSON的表单,则必须在发送字符串时删除[]。您可以使用jQuery函数serializeObject()实现这一点:
var frm = $(document.myform);
var data = JSON.stringify(frm.serializeObject());
$.fn.serializeObject = function() {
var o = {};
//var a = this.serializeArray();
$(this).find('input[type="hidden"], input[type="text"], input[type="password"], input[type="checkbox"]:checked, input[type="radio"]:checked, select').each(function() {
if ($(this).attr('type') == 'hidden') { //If checkbox is checked do not take the hidden field
var $parent = $(this).parent();
var $chb = $parent.find('input[type="checkbox"][name="' + this.name.replace(/\[/g, '\[').replace(/\]/g, '\]') + '"]');
if ($chb != null) {
if ($chb.prop('checked')) return;
}
}
if (this.name === null || this.name === undefined || this.name === '')
return;
var elemValue = null;
if ($(this).is('select'))
elemValue = $(this).find('option:selected').val();
else
elemValue = this.value;
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(elemValue || '');
}
else {
o[this.name] = elemValue || '';
}
});
return o;
}