无法使用jquery和json填充<asp:dropdownlist>

时间:2017-03-31 13:47:02

标签: jquery asp.net json

我正在尝试使用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>");
                });
        });

我无法弄清楚为什么它没有填充,我不知道我错过了什么,因为我是一个完整的新手。感谢您提前获得的任何提示/建议。

1 个答案:

答案 0 :(得分:1)

您有两个问题:

  • 在Scripts / cities.json中你有城市:改为&#34;城市&#34;
  • 在每个循环中你有obj.cities:改为obj.Cities

在任何情况下,您都可以将json声明为库,并将其包含为普通的js。它足以将对象与变量相关联。

摘录:

&#13;
&#13;
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;
&#13;
&#13;