如何将表单的所有元素转换为JavaScript对象?
我希望有某种方法从表单自动构建JavaScript对象,而不必遍历每个元素。我不希望使用$('#formid').serialize();返回的字符串;,我也不希望$('#formid').serializeArray()返回映射;
如何将表单的所有元素转换为JavaScript对象?
我希望有某种方法从表单自动构建JavaScript对象,而不必遍历每个元素。我不希望使用$('#formid').serialize();返回的字符串;,我也不希望$('#formid').serializeArray()返回映射;
当前回答
使用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" />
其他回答
我更喜欢这种方法,因为:您不必遍历2个集合,如果需要,您可以获取除“name”和“value”之外的其他内容,并且可以在将值存储在对象中之前对其进行清理(例如,如果您有不希望存储的默认值)。
$.formObject = function($o) {
var o = {},
real_value = function($field) {
var val = $field.val() || "";
// additional cleaning here, if needed
return val;
};
if (typeof o != "object") {
$o = $(o);
}
$(":input[name]", $o).each(function(i, field) {
var $field = $(field),
name = $field.attr("name"),
value = real_value($field);
if (o[name]) {
if (!$.isArray(o[name])) {
o[name] = [o[name]];
}
o[name].push(value);
}
else {
o[name] = value;
}
});
return o;
}
使用方式如下:
var obj = $.formObject($("#someForm"));
仅在Firefox中测试。
serialize函数将JSON对象作为参数并返回serialize String。
function serialize(object) {
var _SPECIAL_CHARS = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, _CHARS = {
'\b' : '\\b',
'\t' : '\\t',
'\n' : '\\n',
'\f' : '\\f',
'\r' : '\\r',
'"' : '\\"',
'\\' : '\\\\'
}, EMPTY = '', OPEN_O = '{', CLOSE_O = '}', OPEN_A = '[', CLOSE_A = ']', COMMA = ',', COMMA_CR = ",\n", CR = "\n", COLON = ':', space = "", COLON_SP = ': ', stack = [], QUOTE = '"';
function _char(c) {
if (!_CHARS[c]) {
_CHARS[c] = '\\u' + ('0000' + (+(c.charCodeAt(0))).toString(16))
.slice(-4);
}
return _CHARS[c];
}
function _string(s) {
return QUOTE + s.replace(_SPECIAL_CHARS, _char) + QUOTE;
// return str.replace('\"','').replace('\"','');
}
function serialize(h, key) {
var value = h[key], a = [], colon = ":", arr, i, keys, t, k, v;
arr = value instanceof Array;
stack.push(value);
keys = value;
i = 0;
t = typeof value;
switch (t) {
case "object" :
if(value==null){
return null;
}
break;
case "string" :
return _string(value);
case "number" :
return isFinite(value) ? value + EMPTY : NULL;
case "boolean" :
return value + EMPTY;
case "null" :
return null;
default :
return undefined;
}
arr = value.length === undefined ? false : true;
if (arr) { // Array
for (i = value.length - 1; i >= 0; --i) {
a[i] = serialize(value, i) || NULL;
}
}
else { // Object
i = 0;
for (k in keys) {
if (keys.hasOwnProperty(k)) {
v = serialize(value, k);
if (v) {
a[i++] = _string(k) + colon + v;
}
}
}
}
stack.pop();
if (space && a.length) {
return arr
? "[" + _indent(a.join(COMMA_CR), space) + "\n]"
: "{\n" + _indent(a.join(COMMA_CR), space) + "\n}";
}
else {
return arr ? "[" + a.join(COMMA) + "]" : "{" + a.join(COMMA)
+ "}";
}
}
return serialize({
"" : object
}, "");
}
将任何东西变成对象(未经单元测试)
<script type="text/javascript">
string = {};
string.repeat = function(string, count)
{
return new Array(count+1).join(string);
}
string.count = function(string)
{
var count = 0;
for (var i=1; i<arguments.length; i++)
{
var results = string.match(new RegExp(arguments[i], 'g'));
count += results ? results.length : 0;
}
return count;
}
array = {};
array.merge = function(arr1, arr2)
{
for (var i in arr2)
{
if (arr1[i] && typeof arr1[i] == 'object' && typeof arr2[i] == 'object')
arr1[i] = array.merge(arr1[i], arr2[i]);
else
arr1[i] = arr2[i]
}
return arr1;
}
array.print = function(obj)
{
var arr = [];
$.each(obj, function(key, val) {
var next = key + ": ";
next += $.isPlainObject(val) ? array.print(val) : val;
arr.push( next );
});
return "{ " + arr.join(", ") + " }";
}
node = {};
node.objectify = function(node, params)
{
if (!params)
params = {};
if (!params.selector)
params.selector = "*";
if (!params.key)
params.key = "name";
if (!params.value)
params.value = "value";
var o = {};
var indexes = {};
$(node).find(params.selector+"["+params.key+"]").each(function()
{
var name = $(this).attr(params.key),
value = $(this).attr(params.value);
var obj = $.parseJSON("{"+name.replace(/([^\[]*)/, function()
{
return '"'+arguments[1]+'"';
}).replace(/\[(.*?)\]/gi, function()
{
if (arguments[1].length == 0)
{
var index = arguments[3].substring(0, arguments[2]);
indexes[index] = indexes[index] !== undefined ? indexes[index]+1 : 0;
return ':{"'+indexes[index]+'"';
}
else
return ':{"'+escape(arguments[1])+'"';
})+':"'+value.replace(/[\\"]/gi, function()
{
return "\\"+arguments[0];
})+'"'+string.repeat('}', string.count(name, ']'))+"}");
o = array.merge(o, obj);
});
return o;
}
</script>
测试输出:
$(document).ready(function()
{
console.log(array.print(node.objectify($("form"), {})));
console.log(array.print(node.objectify($("form"), {selector: "select"})));
});
on
<form>
<input name='input[a]' type='text' value='text'/>
<select name='input[b]'>
<option>select</option>
</select>
<input name='otherinput[c][a]' value='a'/>
<input name='otherinput[c][]' value='b'/>
<input name='otherinput[d][b]' value='c'/>
<input name='otherinput[c][]' value='d'/>
<input type='hidden' name='anotherinput' value='hidden'/>
<input type='hidden' name='anotherinput' value='1'/>
<input type='submit' value='submit'/>
</form>
将产生:
{ input: { a: text, b: select }, otherinput: { c: { a: a, 0: b, 1: d }, d: { b: c } }, anotherinput: 1 }
{ input: { b: select } }
不使用JQuery序列化深度嵌套表单
在花了几天时间寻找这个没有依赖关系的问题的解决方案之后,我决定使用FormDataAPI制作一个非jQuery表单数据序列化程序。
序列化程序中的逻辑很大程度上基于jQuery插件jQueryBBQ中的de-param函数,然而,在这个项目中,所有依赖项都被删除了。
这个项目可以在NPM和Github上找到:
https://github.com/GistApps/deep-serialize-form
https://www.npmjs.com/package/deep-serialize-form
function deepSerializeForm(form) {
var obj = {};
var formData = new FormData(form);
var coerce_types = { 'true': !0, 'false': !1, 'null': null };
/**
* Get the input value from the formData by key
* @return {mixed}
*/
var getValue = function(formData, key) {
var val = formData.get(key);
val = val && !isNaN(val) ? +val // number
: val === 'undefined' ? undefined // undefined
: coerce_types[val] !== undefined ? coerce_types[val] // true, false, null
: val; // string
return val;
}
for (var key of formData.keys()) {
var val = getValue(formData, key);
var cur = obj;
var i = 0;
var keys = key.split('][');
var keys_last = keys.length - 1;
if (/\[/.test(keys[0]) && /\]$/.test(keys[keys_last])) {
keys[keys_last] = keys[keys_last].replace(/\]$/, '');
keys = keys.shift().split('[').concat(keys);
keys_last = keys.length - 1;
} else {
keys_last = 0;
}
if ( keys_last ) {
for (; i <= keys_last; i++) {
key = keys[i] === '' ? cur.length : keys[i];
cur = cur[key] = i < keys_last
? cur[key] || (keys[i+1] && isNaN(keys[i+1]) ? {} : [])
: val;
}
} else {
if (Array.isArray(obj[key])) {
obj[key].push( val );
} else if (obj[key] !== undefined) {
obj[key] = [obj[key], val];
} else {
obj[key] = val;
}
}
}
return obj;
}
window.deepSerializeForm = deepSerializeForm;
我编写了一个jQuery模块jsForm,即使对于非常复杂的表单(也允许集合和其他更复杂的结构),它也可以实现这种双向。
它使用字段的名称(加上一些用于集合的特殊类)并匹配JSON对象。它允许自动复制用于收集和数据处理的DOM元素:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://raw.github.com/corinis/jsForm/master/src/jquery.jsForm.js"></script>
<script>
$(function(){
// Some JSON data
var jsonData = {
name: "TestName", // Standard inputs
description: "long Description\nMultiline", // Textarea
links: [{href:'http://stackoverflow.com',description:'StackOverflow'}, {href:'http://www.github.com', description:'GitHub'}], // Lists
active: true, // Checkbox
state: "VISIBLE" // Selects (enums)
};
// Initialize the form, prefix is optional and defaults to data
$("#details").jsForm({
data:jsonData
});
$("#show").click(function() {
// Show the JSON data
alert(JSON.stringify($("#details").jsForm("get"), null, " "));
});
});
</script>
</head>
<body>
<h1>Simpel Form Test</h1>
<div id="details">
Name: <input name="data.name"/><br/>
<input type="checkbox" name="data.active"/> active<br/>
<textarea name="data.description"></textarea><br/>
<select name="data.state">
<option value="VISIBLE">visible</option>
<option value="IMPORTANT">important</option>
<option value="HIDDEN">hidden</option>
</select>
<fieldset>
<legend>Links</legend>
<ul class="collection" data-field="data.links">
<li><span class="field">links.description</span> Link: <input name="links.href"/> <button class="delete">x</button></li>
</ul>
</fieldset>
<button class="add" data-field="data.links">add a link</button><br/>
Additional field: <input name="data.addedField"/>
</div>
<button id="show">Show Object</button>
</body>
</html>