我正在尝试使用json和jquery填充下拉列表。我在一个名为“scripts”的项目文件夹中有一个.json文件,我还得到了所有的.js文件。 这是:
{
Cities: [{
"City": "Sofia",
"cityID": "1"
}, {
"City": "Plovdiv",
"cityID": "2"
}, {
"City": "Varna",
"cityID": "3"
}, {
"City": "Burgas",
"cityID": "4"
},
{
"City": "Rousse",
"cityID": "5"
},
{
"City": "Stara Zagora",
"cityID": "6"
},
{
"City": "Pleven",
"cityID": "7"
},
{
"City": "Sliven",
"cityID": "8"
},
{
"City": "Dobrich",
"cityID": "9"
},
{
"City": "Shumen",
"cityID": "10"
}]
}
这是我在页面上的js。
$(document).ready(function () {
$.getJSON("Scripts/cities.json", function (obj) {
$.each(obj.cities, function (key, value) {
$("#db_City").append("<option>" + value.City + "</option>");
});
});
我无法弄清楚为什么它没有填充,我不知道我错过了什么,因为我是一个完整的新手。感谢您提前获得的任何提示/建议。
答案 0 :(得分:1)
您有两个问题:
在任何情况下,您都可以将json声明为库,并将其包含为普通的js。它足以将对象与变量相关联。
摘录:
var obj = {
Cities: [{
"City": "Sofia",
"cityID": "1"
}, {
"City": "Plovdiv",
"cityID": "2"
}, {
"City": "Varna",
"cityID": "3"
}, {
"City": "Burgas",
"cityID": "4"
},
{
"City": "Rousse",
"cityID": "5"
},
{
"City": "Stara Zagora",
"cityID": "6"
},
{
"City": "Pleven",
"cityID": "7"
},
{
"City": "Sliven",
"cityID": "8"
},
{
"City": "Dobrich",
"cityID": "9"
},
{
"City": "Shumen",
"cityID": "10"
}]
};
//$.getJSON("..../data.json", function (obj) {
$.each(obj.Cities, function (key, value) {
$("#db_City").append("<option>" + value.City + "</option>");
});
//});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="db_City"></select>
&#13;