Build a select from a json file in PHP or JS

时间:2015-06-25 19:10:01

标签: javascript php json

How can I build a select with from a json file like this ? { "AF": "Afghanistan", "AL": "Albania", "DZ": "Algeria", "AS": "American Samoa", ... } I'm trying to make something like this: <select> <option value="AF">Afghanistan</option> <option value="AL">Albania</option> </select> Thanks.

3 个答案:

答案 0 :(得分:1)

如果您使用的是Javascript,则应使用Ajax获取JSON数据。然后假设我们已经拥有数据“JSON”,您可以使用循环来处理它,例如:

var json_data = {
    "AF": "Afghanistan",
    "AL": "Albania",
    "DZ": "Algeria",
    "AS": "American Samoa"
};

var select = document.querySelector("#mySelect");

for(var countryCode in json_data){
   var option = new Option(json_data[countryCode], countryCode);
   select.appendChild(option);
}
<select id="mySelect"></select>

使用jQuery:

jQuery简化了您的工作,您使用jQuery.getJSON()方法从文件中获取JSON数据,使用jQuery.each()来处理对象

$.getJSON("https://raw.githubusercontent.com/tarraq/JSON-data-arrays/master/countries/english/countries-key-value.json", function(jsonData){
   var select = $("#mySelect");
   $.each(jsonData, function(key, country){
      select.append($("<option>", {value: key, text: country}))
   })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<select id="mySelect"></select>

答案 1 :(得分:0)

这将在PHP中发挥作用。采用JSON编码的字符串并将其转换为PHP数组。迭代数组以生成所有选择选项。

<?php

$json = '{
    "AF": "Afghanistan",
    "AL": "Albania",
    "DZ": "Algeria",
    "AS": "American Samoa"
}';

$decoded = json_decode($json, true)
?>

</select>   
    <?  foreach($decoded as $key => $value){?>

        <option value="<? echo $key; ?>"><? echo $value; ?></option>

    <?  }   ?>

<select>

答案 2 :(得分:0)

var myJason = {"AF": "Afghanistan","AL": "Albania","DZ": "Algeria","AS": "American Samoa"}



$.each(myJson,function(key,val) {
$('#mySelect').append('<option value="'+ key + '">' + val + '</option>');
});