Javascript 用 json 填充下拉列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6532791/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fill dropdown list with json
提问by Tara
I have SQLite table with columns id and name. I return array of those rows like json from autocomplete.php page. How to fill select with options ( drop down list ) with this json using jquery and JavaScript ? I am new to JavaScript and JQuery, I googled but didn't find how. In ASP.NET this is easy but here I don't know. Would somebody help ?
我有包含 id 和 name 列的 SQLite 表。我从 autocomplete.php 页面返回这些行的数组,如 json。如何使用 jquery 和 JavaScript 用这个 json 填充选项(下拉列表)?我是 JavaScript 和 JQuery 的新手,我用谷歌搜索但没有找到方法。在 ASP.NET 中,这很容易,但在这里我不知道。有人会帮忙吗?
This is example of my JSON, can be much longer.
这是我的 JSON 示例,可以更长。
[
{
"id": "1",
"name": "test"
},
{
"id": "1",
"name": "test"
}
]
回答by Ashish
HTML:
HTML:
<select id="sel">
</select>
JavaScript:
JavaScript:
$(function() {
var data = [
{
"id": "1",
"name": "test1"},
{
"id": "2",
"name": "test2"}
];
$.each(data, function(i, option) {
$('#sel').append($('<option/>').attr("value", option.id).text(option.name));
});
})
Here's a working example. http://jsfiddle.net/ms2Ma/
这是一个工作示例。http://jsfiddle.net/ms2Ma/
回答by Sumit Raju
Try this, This will give you an option to have any number of dropdown boxes and JSON nodes to configure dropdown boxes.
试试这个,这会给你一个选项,让你有任意数量的下拉框和 JSON 节点来配置下拉框。
You need to follow few steps:
您需要执行以下几个步骤:
- Create an array of dropdown boxes.(e.g. if you have to configure a phone then you should be using dropdown of color, memory etc.)
- Create a JSON object as it is created in code. Dont change the configurable items name which starts with "level1" and end with any number of nodes, As it has to be sync with the index of items of array you are creating in the first place.
- 创建一系列下拉框。(例如,如果您必须配置手机,那么您应该使用颜色、内存等下拉菜单)
- 在代码中创建一个 JSON 对象。不要更改以“level1”开头并以任意数量的节点结尾的可配置项名称,因为它必须与您首先创建的数组项的索引同步。
Here is the data:
这是数据:
var Dropdowns = ["Model", "Color", "Memory","design","covers","music"];
var Data ={"phones":[
{
"oid":":000000F0:00000458:",
"level1":"3G",
"level2":"white",
"level3":"16GB",
"level4":"slim",
"level5":"Back cover",
"level6":"headphone",
"price":"£568.63",
"addToCart":"#Cart1"
},
{
"oid":":000000F0:000003DA:",
"level1":"3G",
"level2":"black",
"level3":"16GB",
"level4":"slim",
"level5":"Flip cover",
"level6":"headphone",
"price":"£615.79",
"addToCart":"#Cart7"
}]};
See the full working code here: https://jsfiddle.net/raju_sumit/681ppgq0/5/
在此处查看完整的工作代码:https: //jsfiddle.net/raju_smit/681ppgq0/5/
回答by u9954860
Try this :)
尝试这个 :)
Javascript:
Javascript:
$.getJSON("/array.json",
function (json) {
$.each(json,
function (key, value) {
$("#id-select").append("<option value='" + value.c + "'>" + value.d + "</option>");
});
});