javascript - 将 JSON 对象显示为下拉列表中的选项

标签 javascript html json html-select

我有一个简单的 HTML 页面,我想在其中从 JSON 文件读取对象并使用 JavaScript 将它们显示为下拉列表中的选项。 HTML 和 JSON 如下:

HTML

<html>
  <body>
    <select id="myid">MyList</select>
    <script src="myscript.js"></script>
  </body>
</html>

JSON

[{"Mode":"CARD"},
{"Mode":"CASH"},
{"Mode":"CHEQUE"}];

任何帮助。非常感谢 JavaScript!

最佳答案

工作和测试代码,要使用 JavaScript 读取外部本地 JSON 文件 (data.json),首先使用以下数据创建 data.json 文件:

data = '[{"Mode":"CARD"}, {"Mode":"CASH"}, {"Mode":"CHEQUE"}]';

在脚本标签中提及JSON文件的路径

<html>
    <script type="text/javascript" src="data.json"></script>
    <script>
        function addOptions(){
            var jsonArray = JSON.parse(data);
            var select = document.getElementById('dd');
            var option;
            for (var i = 0; i < jsonArray.length; i++) {
              option = document.createElement('option');
              option.text = jsonArray[i]["Mode"];
              select.add(option);
            }
        }
    </script>
    <body onload="addOptions();">
        <select id="dd"></select>
    </body>
</html>

关于javascript - 将 JSON 对象显示为下拉列表中的选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31587233/

相关文章:

java - 使用 Jackson 将 JSON 数组反序列化为单个 Java 对象

java.lang.ClassCastException : org. json.simple.JSONArray 无法转换为 org.json.JSONArray

CSS : Center Element in div containing floats

javascript - Sencha Touch AJAX 调用 MVC

javascript - 如何使用JQuery在SharePoint中停止音频/视频?

javascript - Web Audio API 故障/失真问题

javascript - 正则表达式,获取子模式

c# - JSON 数组而不是字符串

javascript - Jquery 移动预加载页面停止工作

html - 卡住的表格列在纯 CSS 中无法正常工作