【问题标题】:Populate select drop-down with json使用 json 填充选择下拉列表
【发布时间】:2015-08-24 04:18:57
【问题描述】:

使用 jquery,我正在尝试使用 json 填充选择下拉列表。我正在尝试从下面的 json 中显示国家/地区列表...

{  
"country":[  
  {  
     "China":[  
        {  
           "tarrifType":"Pay as you go"
        },
        {  
           "fixLine":"23p"
        }
     ],
     "India":[  
        {  
           "sms":"39p"
        },
        {  
           "fixLine":"3p",
           "sms":"59p"
        }
     ],
     "Poland":[  
        {  
           "mobile":"29p",
           "sms":"19p"
        },
        {  
           "tarrifType":"China Pass",
           "fixLine":"23p"
        }
     ]
  }
]
}

到目前为止,我尝试使用的 jquery 如下...

 $.getJSON("js/widgets/country-picker.json", function(result){
   $.each(result, function(i, field) {
  $('#js-rate-select').append($('<option>').text(field[1]).attr('value',    field[1]));
  });
 });

但它不会填充选择下拉菜单或给出任何 DOM 错误。有什么建议我可以解决这个问题吗?我认为问题在于 json 格式 - 我可以更改谢谢

【问题讨论】:

  • 你真正想要选择的json的哪一部分?国家名称或每个国家的一部分?

标签: jquery json


【解决方案1】:

您的 json 提要返回一个仅包含一个索引的数组,该索引是具有不同国家/地区的对象。因此,你应该说

result.country[0].China.tarrifType.

而且,您可以像这样迭代国家/地区:

$.each(result.country[0], function(country,data) { console.log(country); }

虽然,我建议重做您的 JSON。你可以这样做:

var result = {
    "country": {
        "China": {
            "tarrifType": "Pay as you go",
            "fixLine": "23p"
        },
        "India": {
            "sms": "39p",
            "fixLine": "3p",
            "sms": "59p"
        },
        "Poland": {
            "mobile": "29p",
            "sms": "19p",
            "tarrifType": "China Pass",
            "fixLine": "23p"
        }
    }
};


$(function () {
    $.each(result.country, function (country, data) {
        console.log("Country : " + country);
        console.log(data); // data.fixLine, data.tarrifType, data.sms

        $('#selectbox').append('<option value="' + country + '">' + country + '</option>');

    });
});

jsfiddle 在这里: Link to JSfiddle

【讨论】:

  • 非常感谢您的帮助和花时间做一个小提琴。我还按照建议更改了 json 结构,并且运行良好。非常感谢。
猜你喜欢
  • 1970-01-01
  • 2021-01-28
  • 1970-01-01
  • 1970-01-01
  • 2015-06-28
  • 1970-01-01
  • 2012-09-26
  • 1970-01-01
相关资源
最近更新 更多