我有一串数据通过ajax到达页面。格式如下
[{"servername":"svrA"},{"servername":"svrB"},{"servername":"svrC"},{"location":"locA"},{"location":"locB"},{"location":"locC"}]
我想用数据填充两个选择框。
我尝试了以下伪代码的不同变体:
for each item in the json string
if obj == servername
add to selectbox Server
if obj == location
add to selectbox Location
任何想法将不胜感激。谢谢。
最佳答案
var stuff = [{"servername":"svrA"},{"servername":"svrB"},{"servername":"svrC"},{"location":"locA"},{"location":"locB"},{"location":"locC"}];
var elems = {
"servername": jQuery('#select-server'),
"location": jQuery('#select-location')
};
stuff.forEach(function(item){
for(var selectName in elems){
if(typeof item[selectName] != 'undefined'){
var val = item[selectName];
elems[selectName].append(jQuery('<option/>').val(val).html(val));
}
}
});
并不是说 forEach
在旧版浏览器上不可用。上面的代码只是供您使用的示例。
关于javascript - 使用单个 json 字符串填充多个选择框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18433638/