如何将表单的所有元素转换为JavaScript对象?
我希望有某种方法从表单自动构建JavaScript对象,而不必遍历每个元素。我不希望使用$('#formid').serialize();返回的字符串;,我也不希望$('#formid').serializeArray()返回映射;
如何将表单的所有元素转换为JavaScript对象?
我希望有某种方法从表单自动构建JavaScript对象,而不必遍历每个元素。我不希望使用$('#formid').serialize();返回的字符串;,我也不希望$('#formid').serializeArray()返回映射;
当前回答
所以我使用了公认的答案,发现了一个主要缺陷。它不支持以下输入数组:
<input type="checkbox" name="array[]" value="1"/>
<input type="checkbox" name="array[]" value="2"/>
<input type="checkbox" name="array[]" value="3"/>
这一小改动应该可以解决以下问题:
function objectifyForm(inp){
var rObject = {};
for (var i = 0; i < inp.length; i++){
if(inp[i]['name'].substr(inp[i]['name'].length - 2) == "[]"){
var tmp = inp[i]['name'].substr(0, inp[i]['name'].length-2);
if(Array.isArray(rObject[tmp])){
rObject[tmp].push(inp[i]['value']);
} else{
rObject[tmp] = [];
rObject[tmp].push(inp[i]['value']);
}
} else{
rObject[inp[i]['name']] = inp[i]['value'];
}
}
return rObject;
}
记住将$(this).serializeArray()的输出传递给它;否则它不会起作用。
其他回答
这将处理具有相同名称的多个select或偶数元素:
$.fn.formToJSON = function(){
pairStr=this.serialize();
let rObj={};
pairStr.split(`&`).forEach((vp)=> {
prop=vp.split(`=`)[0];
val=vp.split(`=`)[1];
if(rObj.hasOwnProperty(prop)) {
if (Array.isArray(rObj[prop])) {
rObj[prop].push(val);
} else {
rObj[prop]=[rObj[prop]];
rObj[prop].push(val);
}
} else {
rObj[prop]=val;
}
});
return JSON.stringify(rObj);
}
此线程似乎已成为表单序列化的常见问题解答:)
我对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);
此函数返回转换为正确类型的所有值;
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);
将任何东西变成对象(未经单元测试)
<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模块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>