我创建了一个简单的javascript插件,它允许我从特定的html元素中收集数据。页面可以包含x个元素(通常最多20个),每个元素都有自己的设置。我的问题是返回的对象不是有效的JSON格式,因为我收到错误“多个JSON根元素”。
我认为原因是因为我在插件中使用的每个函数,它为每个对象创建一个新对象,我试图解决这个问题;结果不好。
所有帮助都将受到高度赞赏,提前感谢!
示例插件
(function($) {
$.fn.collect_data = function() {
this.each(function() {
var id = "#" + ($(this).attr("id"));
// Get numerical value of id
var get_package_id = function() {
var package_id = id.replace(/[^0-9]/g, '');
return package_id;
}
// Packages is the top level container
var get_packages = function() {
var packages = {};
packages = ({[get_package_id()]: {}});
return packages;
}
// Demo information for each invidual package
var get_package_info = function() {
var info = {};
$(id).each(function() {
info = ({
value: 'Some value',
another_value: 'Another value'
});
});
return info;
}
// Demo information for each invidual package
var get_more_info = function() {
var more_info = {};
$(id).each(function() {
more_info = ({
value_more_info: 'Some value',
another_value_more_info: 'Another value'
});
});
return more_info;
}
// Combine the demo information
var result = function() {
var packages = get_packages();
var info = get_package_info();
var more_info = get_more_info();
packages[get_package_id()].info = info;
packages[get_package_id()].more_info = more_info;
return packages;
}
$("#show-data").append(JSON.stringify(result(), null, 2));
});
return this;
}
}(jQuery));
结果无效
{
"33": {
"info": {
"value": "Some value",
"another_value": "Another value"
},
"more_info": {
"value_more_info": "Some value",
"another_value_more_info": "Another value"
}
}
}{
"74": {
"info": {
"value": "Some value",
"another_value": "Another value"
},
"more_info": {
"value_more_info": "Some value",
"another_value_more_info": "Another value"
}
}
}{
"99": {
"info": {
"value": "Some value",
"another_value": "Another value"
},
"more_info": {
"value_more_info": "Some value",
"another_value_more_info": "Another value"
}
}
}{
"124": {
"info": {
"value": "Some value",
"another_value": "Another value"
},
"more_info": {
"value_more_info": "Some value",
"another_value_more_info": "Another value"
}
}
}{
"124": {
"info": {
"value": "Some value",
"another_value": "Another value"
},
"more_info": {
"value_more_info": "Some value",
"another_value_more_info": "Another value"
}
}
}
所有数据应该在顶级{}容器内,而不是在自己的{}内添加每个对象。
提前感谢所有帮助
答案 0 :(得分:0)
谈论完全过度设计的代码。所有那些只被调用一次的函数有什么意义?为什么要制作一个你无法重复使用的插件?
让我们将您的代码放入其实际行为:
var data = $("foo").map(function () {
return {
package_id: "#" + this.id.replace(/[^0-9]/g, ''),
info: {
value: 'Some value',
another_value: 'Another value'
},
more_info: {
value_more_info: 'Some value',
another_value_more_info: 'Another value'
}
};
}).toArray();
$("#show-data").text(JSON.stringify(data, null, 2));
旁注:
不要使用这样的数据结构:
{
"uniqueID1": {"some": "data"},
"uniqueID2": {"some": "data"},
"uniqueID3": {"some": "data"}
}
将对象误用为数组。
在这种情况下,您真正想要创建的是一个数组。它将使所有相关方更容易生活 。
[
{"id": "uniqueID1", "some": "data"},
{"id": "uniqueID2", "some": "data"},
{"id": "uniqueID3", "some": "data"}
]