使用 jquery,我尝试使用 json 填充选择下拉列表。我正在尝试显示下面 json 中的国家/地区列表...
{
"country":[
{
"China":[
{
"tarrifType":"Pay as you go"
},
{
"fixLine":"23p"
}
],
"India":[
{
"sms":"39p"
},
{
"fixLine":"3p",
"sms":"59p"
}
],
"Poland":[
{
"mobile":"29p",
"sms":"19p"
},
{
"tarrifType":"China Pass",
"fixLine":"23p"
}
]
}
]
}
到目前为止,我尝试使用的 jquery 如下......
$.getJSON("js/widgets/country-picker.json", function(result){
$.each(result, function(i, field) {
$('#js-rate-select').append($('<option>').text(field[1]).attr('value', field[1]));
});
});
但它不会填充选择下拉列表或给出任何 DOM 错误。有什么建议我可以解决这个问题吗?我认为问题是因为 json 格式 - 我可以更改谢谢
最佳答案
您的 json feed 返回一个仅包含一个索引的数组,该索引是一个具有不同国家/地区的对象。因此,你应该说
result.country[0].China.tarrifType.
而且,您可以像这样迭代国家/地区:
$.each(result.country[0], function(country,data) { console.log(country); }
不过,我建议重做您的 JSON。你可以这样做:
var result = {
"country": {
"China": {
"tarrifType": "Pay as you go",
"fixLine": "23p"
},
"India": {
"sms": "39p",
"fixLine": "3p",
"sms": "59p"
},
"Poland": {
"mobile": "29p",
"sms": "19p",
"tarrifType": "China Pass",
"fixLine": "23p"
}
}
};
$(function () {
$.each(result.country, function (country, data) {
console.log("Country : " + country);
console.log(data); // data.fixLine, data.tarrifType, data.sms
$('#selectbox').append('<option value="' + country + '">' + country + '</option>');
});
});
jsfiddle在这里: Link to JSfiddle
关于jquery - 使用 json 填充选择下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30730496/