【问题标题】:Populate dropDownList from a JSon Array从 JSon 数组填充 dropDownList
【发布时间】:2016-04-21 15:41:47
【问题描述】:

我正在尝试根据从 Web 服务获取的 JSON 数组填充 dropDownList。

这是我得到的 Json 数组的示例:

[{"id":1,"name":"AJ Shaw"},{"id":2,"name":"Jay Black"}]

这是我用来尝试加载 dropDownList 的 javascript

function load_level1() {
        $.ajax({
            url: '<%=ResolveUrl("/facility/getTaxLevel1_LOV")%>',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            method: "GET",
            success: function (Result) {
                $.each(Result, function(key, value) {
                    $("#level1").append($("<option></option>").val
                        (value).html(value));
                });
            },
            error: function (Result) {
                alert("Error");
            },
            failure: function (Result) {
                alert(response.responseText);
            }
        });
    }

这是我的 dropDownList 对象:

<asp:DropDownList ID="level1" runat="server" AppendDataBoundItems="true" ><asp:ListItem Selected="True" Value="Select Level 1" ></asp:ListItem></asp:DropDownList>

我只想用 Id 和名称填充 dropDownList。不可能那么难,但我迷路了。有什么建议吗?

【问题讨论】:

  • &lt;asp:DrownDownList&gt; 是一个服务器端组件。是否可以在服务器上加载项目,而不是在客户端(通过 AJAX)?

标签: c# jquery asp.net json ajax


【解决方案1】:

在成功函数 ajax 请求中试试这个

$.each(Result,function(key,value){ 
  $("#level1").append($("<option></option>").val(value.id).html(value.name));
});

【讨论】:

  • 它仍然没有填充我的下拉列表。查看 Chrome 调试器我收到一些关于“jquery-1.10.2.min.js:21 Uncaught TypeError: Cannot use 'in' operator to search'1047' in [{"id":1,"name" :.....}]
  • 验证您的 json 中没有无效字符。尝试执行此代码。 $.each([{"id":1,"name":"AJ Shaw"},{"id":2,"name":"Jay Black"}],function(key,value){ console.log(value.name) });
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-08
  • 2023-03-06
相关资源
最近更新 更多