我有以下数据库表(虽然数据库中有更多数据,但这不是全部!):
catid value description
0 350 350 euro
0 500 500 euro
0 650 650 euro
1 0 No
1 1 Yes
在PHP和json_encode()的帮助下,我正在创建该表的JSON字符串:
jQuery171024539993586950004_1349776890005([{"0":"0","catid":"0","1":"350","value":"350","2":"350 euro","description":"350 euro"},{"0":"0","catid":"0","1":"500","value":"500","2":"500 euro","description":"500 euro"},{"0":"0","catid":"0","1":"650","value":"650","2":"650 euro","description":"650 euro"},{"0":"1","catid":"1","1":"0","value":"0","2":"No","description":"No"},{"0":"1","catid":"1","1":"1","value":"1","2":"Yes","description":"Yes"}])
现在我想要的是使用JSON来填充选择框,就像在HTML中一样:
<select id="0">
<option value="350">350 euro</option>
<option value="500">500 euro</option>
<option value="650">650 euro</option>
</select>
<select id="1">
<option value="0">No</option>
<option value="1">Yes</option>
</select>
任何人都可以帮我吗?我知道怎么做一个循环来填充一个表(使用$ .getJSON),但我有点坚持这个。
答案 0 :(得分:2)
此功能将遍历您发布的对象并填充菜单(给定您发布的来源):
var populateSelects = function(data) {
var cat0 = $('select#0'),
cat1 = $('select#1'),
opt = $('<option />'),
newOpt = {},
cat0opts = [],
cat1opts = [];
$.each(data, function(i, obj) {
//clone the option element so as to not re-create a new one
newOpt = opt.clone();
//obj is the JavaScript object in the array, so
//dot-notation works nicely
newOpt.text(obj.description).val(obj.value);
if (obj.catid === "0") {
//push the DOM element, not the jQuery object
cat0opts.push(newOpt[0]);
} else if (obj.catid === "1") {
cat1opts.push(newOpt[0]);
}
});
//Add the array of DOM elements to their respective menus,
//clearing out any existing menu items.
cat0.empty().append(cat0opts);
cat1.empty().append(cat1opts);
};
这里有一个小提琴:http://jsfiddle.net/a5MTE/1/
一个重要的注意事项是catid
比较...如果解析的JSON将catid
作为数字(不是字符串)返回,则您需要将比较更改为if (obj.catid === 0)
。
答案 1 :(得分:0)
通过json解析你应该做一个解析器,通过addcat上的if和else条件,你将能够做到这一点