【问题标题】:How to populate a json file values as select option in HTML如何将 json 文件值填充为 HTML 中的选择选项
【发布时间】:2018-09-21 11:25:18
【问题描述】:

我有一个 python 文件,它返回一个 json 文件。它只包含一个这样的列表:[1,2,3,4,5,6,7,] 如何使它填充到 HTML 页面的选择框中。

代码:

$.getJSON('data.json', function(data) {
    destinations = data[]

    $.each(destinations, function(id, destination) {
        destination = destination[]
    })
});

要做什么?

【问题讨论】:

  • 不确定您想要什么,但这不可能是正确的:destination = destination[], that,或者您的数据将类似于 [[[1],[2],[3] ]]?然后我仍然希望分配包含数组中位置的键,例如destination = destination[0]。
  • 也许您应该包含 jQuery 标记并删除 python 标记,因为它似乎与提供 json 的进程无关。

标签: javascript python html json


【解决方案1】:

Previously answered here

$.getJSON('data.json', function(data) {
  var sel = $('<select>').appendTo('body');
  $(data).each(function() {
   sel.append($("<option>").attr('value',this).text(this));
  });
});

在您的情况下,不是 this.val 和 this.text,因为您的数组不包含对象,而只包含整数。

【讨论】:

  • 数据只有这个:[1,2,3,4,5]
【解决方案2】:

试试这个:

$.getJSON('data.json', function(data) {
    destinations = data[];

    $("#selectid").clear();
    $.each(destinations, function(id, destination) {
        $("#selectid").append("<option value="+destination[id]+">"+destination[id]+"</option>");
    });
});

希望这是你的期望

【讨论】:

    猜你喜欢
    • 2018-03-01
    • 1970-01-01
    • 2019-10-09
    • 1970-01-01
    • 2017-12-12
    • 2022-08-05
    • 1970-01-01
    • 2017-03-31
    • 2017-12-28
    相关资源
    最近更新 更多