如何将表单的所有元素转换为JavaScript对象?
我希望有某种方法从表单自动构建JavaScript对象,而不必遍历每个元素。我不希望使用$('#formid').serialize();返回的字符串;,我也不希望$('#formid').serializeArray()返回映射;
如何将表单的所有元素转换为JavaScript对象?
我希望有某种方法从表单自动构建JavaScript对象,而不必遍历每个元素。我不希望使用$('#formid').serialize();返回的字符串;,我也不希望$('#formid').serializeArray()返回映射;
当前回答
这里最简单。我用一个简单的字符串替换了一个正则表达式,到目前为止,它们就像一个符咒。我不是正则表达式专家,但我打赌您甚至可以填充非常复杂的对象。
var values = $(this).serialize(),
attributes = {};
values.replace(/([^&]+)=([^&]*)/g, function (match, name, value) {
attributes[name] = value;
});
其他回答
如果要发送带有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;
}
此函数应处理多维数组以及多个同名元素。
到目前为止,我已经使用了几年:
jQuery.fn.serializeJSON=function() {
var json = {};
jQuery.map(jQuery(this).serializeArray(), function(n, i) {
var _ = n.name.indexOf('[');
if (_ > -1) {
var o = json;
_name = n.name.replace(/\]/gi, '').split('[');
for (var i=0, len=_name.length; i<len; i++) {
if (i == len-1) {
if (o[_name[i]]) {
if (typeof o[_name[i]] == 'string') {
o[_name[i]] = [o[_name[i]]];
}
o[_name[i]].push(n.value);
}
else o[_name[i]] = n.value || '';
}
else o = o[_name[i]] = o[_name[i]] || {};
}
}
else {
if (json[n.name] !== undefined) {
if (!json[n.name].push) {
json[n.name] = [json[n.name]];
}
json[n.name].push(n.value || '');
}
else json[n.name] = n.value || '';
}
});
return json;
};
像boss一样将表单转换为JSON
目前的来源是GitHub和Bower。
$bower安装jquery序列化对象
以下代码现已弃用。
以下代码可以处理所有类型的输入名称;按照你的预期处理它们。
例如:
<!-- All of these will work! -->
<input name="honey[badger]" value="a">
<input name="wombat[]" value="b">
<input name="hello[panda][]" value="c">
<input name="animals[0][name]" value="d">
<input name="animals[0][breed]" value="e">
<input name="crazy[1][][wonky]" value="f">
<input name="dream[as][vividly][as][you][can]" value="g">
// Output
{
"honey":{
"badger":"a"
},
"wombat":["b"],
"hello":{
"panda":["c"]
},
"animals":[
{
"name":"d",
"breed":"e"
}
],
"crazy":[
null,
[
{"wonky":"f"}
]
],
"dream":{
"as":{
"vividly":{
"as":{
"you":{
"can":"g"
}
}
}
}
}
}
用法
$('#my-form').serializeObject();
魔法(JavaScript)
(function($){
$.fn.serializeObject = function(){
var self = this,
json = {},
push_counters = {},
patterns = {
"validate": /^[a-zA-Z][a-zA-Z0-9_]*(?:\[(?:\d*|[a-zA-Z0-9_]+)\])*$/,
"key": /[a-zA-Z0-9_]+|(?=\[\])/g,
"push": /^$/,
"fixed": /^\d+$/,
"named": /^[a-zA-Z0-9_]+$/
};
this.build = function(base, key, value){
base[key] = value;
return base;
};
this.push_counter = function(key){
if(push_counters[key] === undefined){
push_counters[key] = 0;
}
return push_counters[key]++;
};
$.each($(this).serializeArray(), function(){
// Skip invalid keys
if(!patterns.validate.test(this.name)){
return;
}
var k,
keys = this.name.match(patterns.key),
merge = this.value,
reverse_key = this.name;
while((k = keys.pop()) !== undefined){
// Adjust reverse_key
reverse_key = reverse_key.replace(new RegExp("\\[" + k + "\\]$"), '');
// Push
if(k.match(patterns.push)){
merge = self.build([], self.push_counter(reverse_key), merge);
}
// Fixed
else if(k.match(patterns.fixed)){
merge = self.build([], k, merge);
}
// Named
else if(k.match(patterns.named)){
merge = self.build({}, k, merge);
}
}
json = $.extend(true, json, merge);
});
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 } }
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"}