【问题标题】:Having trouble populating <asp:DropDownList> with jquery and json使用 jquery 和 json 填充 <asp:DropDownList> 时遇到问题
【发布时间】:2017-03-31 13:47:01
【问题描述】:

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

我不知道为什么它没有填充,我不知道我缺少什么,因为我是一个完全的新手。感谢您提前获得的任何提示/建议。

【问题讨论】:

  • 就 JavaScript 和 jQuery 而言,没有 asp:DropDownList 这样的东西。这只是普通的 HTML。因此,请查看浏览器中的实际 HTML。并确保您的 ID 匹配。在您的 JavaScript 控制台中查找错误。另外,如果您是第一次学习 ASP.NET,为什么还要在 Web 窗体上浪费时间?该框架正在消亡。学习MVC

标签: jquery asp.net json


【解决方案1】:

你有两个问题:

  • 在 Scripts/cities.json 中有 Cities:更改为“Cities”
  • 在每个循环中都有 obj.cities:更改为 obj.Cities

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

sn-p:

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>");
    });
//});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<select id="db_City"></select>

【讨论】:

  • 感谢您,解决了 2 个问题,使下拉列表完美运行。
  • :) 很高兴为您提供帮助
猜你喜欢
  • 2020-02-23
  • 1970-01-01
  • 2022-01-04
  • 1970-01-01
  • 2013-09-28
  • 1970-01-01
  • 2011-05-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多