我正在尝试动态地将表单内容放入 JSON 中。 它之前有效,但是在我添加了一个额外的层(数组中的数组)之后,似乎我做错了一些事情:
aJSON = {};
aJSON['properties'] = [];
aJSON['options'] = [];
aJSON['arrays'] = [];
$('input').each(function () {
if($(this).attr('name') != undefined) {
if($(this).attr('name').indexOf('[]') > -1) {
if(aJSON['arrays'][$(this).attr('name')] == undefined) {
aJSON['arrays'][$(this).attr('name')] = [];
}
if($(this).is(':checked')) {
aJSON['arrays'][$(this).attr('name')][$(this).attr('value')] = 1;
} else {
aJSON['arrays'][$(this).attr('name')][$(this).attr('value')] = 0;
}
} else {
aJSON['properties'][$(this).attr('name')] = $(this).val();
}
}
});
$('select').each(function () {
if($(this).attr('name') != undefined) {
aJSON['properties'][$(this).attr('name')] = $(this).val();
}
});
var array = getUrlVars();
aJSON['options']['type'] = array['type'];
aJSON['options']['id'] = array['id'];
aJSON['options']['view'] = pageSpecificVariables['view'];
上面4行只是尝试,我也尝试过:
aJSON = {'properties':[], 'options':[], 'arrays':[]}
但我得到的唯一结果是一个带有空属性、选项和数组数组的对象。
在我将所有值直接放入 aJSON 中之前,效果非常好。 但为了分类,我需要存在 3 个类别。
知道为什么我的值没有写入 aJSON 吗?
编辑
在此处添加了 JSfiddle:http://jsfiddle.net/abayob/pob32fs1/
最佳答案
我假设您正在尝试序列化表单。
使用 jQuery 的 serializeArray 函数代替
var myform = $("#myform");
var data = JSON.stringify( myform.serializeArray() );
更新
因为您尝试使用数组
,例如对象映射
解决方案: http://jsfiddle.net/pob32fs1/8/
var oJSON = {
properties: {},
options: {},
arrays: {}
};
$('input[name]').each(function(){
var $el = $(this),
value = $el.attr("value"),
name = $el.attr('name');
if(name.indexOf('[]') >= 0)
{
oJSON.arrays[name] = oJSON.arrays[name] || {};
oJSON.arrays[name][value] = $el.is(':checked') ? 1 : 0;
} else {
oJSON.properties[name] = $el.val();
}
});
$('select[name]').each(function(){
var $el = $(this);
oJSON.properties[$el.attr('name')] = $el.val();
});
oJSON.options['type'] = 'user';
oJSON.options['id'] = 1;
oJSON.options['view'] = 'user-settings';
console.log(oJSON);
关于javascript - 动态定义 JSON - 找不到我做错了什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33523248/