Javascript 使用 jQuery、JSON 和 AJAX 填充下拉列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3564333/
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
Using jQuery, JSON and AJAX to populate a drop down
提问by Odyss3us
like the title says, I am trying to create a drop down menu using jQuery, JSON and AJAX, although I am familiar with the theory I have yet to put it into practice, any advice, demo code snippets or tutorials would be appreciated, since I would like to get off to the best possible start!
正如标题所说,我正在尝试使用 jQuery、JSON 和 AJAX 创建一个下拉菜单,尽管我熟悉我尚未将其付诸实践的理论,任何建议、演示代码片段或教程将不胜感激,因为我想有一个最好的开始!
Thanx in advance!
提前谢谢!
回答by Kwastie
This should do the trick:
这应该可以解决问题:
$.getJSON("test.php", function(data){
$.each(data, function(index, text) {
$('#mySelect').append(
$('<option></option>').val(index).html(text)
);
});
});
note: test.php should return an json encoded array
注意:test.php 应该返回一个 json 编码的数组
回答by Ayaz Alavi
You need to do $.getJSON call to fetch json from server on document.load or on some other event http://api.jquery.com/jQuery.getJSON/. After that you have to loop through the data and append it to your select box. see that http://www.jsfiddle.net/Dyc9Y/1/
您需要执行 $.getJSON 调用以在 document.load 或其他一些事件http://api.jquery.com/jQuery.getJSON/上从服务器获取 json 。之后,您必须遍历数据并将其附加到您的选择框。看到http://www.jsfiddle.net/Dyc9Y/1/
<select id="fillME"></select>
<button id="startFilling" value="">Start ajax</button>
$(function(){
var json = {
"0": {"title":"localjsonOPtion1", "value":"b"},
"1": {"title":"localjsonOPtion2", "value":"a"}
};
$("#startFilling").click(function(){
$.getJSON("http://localdev.myvouchercodes.co.uk/local/default/search/jsonresponse", function(data){
$("#fillME").html("");
for(key in data)
$("#fillME").append("<option value='"+json [key].value+"'>"+json[key].title+"</option>");
for(key in json)
$("#fillME").append("<option value='"+json [key].value+"'>"+json[key].title+"</option>");
});
});
});
offcourse above example depends on json with following format.
offcourse 上面的例子取决于具有以下格式的json。
{
"0": {"title":"option1", "value":"1"},
"1": {"title":"option2", "value":"2"}
}
EDITED:You also need to be familiar with select box change event http://api.jquery.com/change/and :selected selectorthat will allow you to fetch selected option from the selectbox
http://api.jquery.com/selected-selector/like $("select option:selected")
编辑:您还需要熟悉选择框更改事件http://api.jquery.com/change/和:选择选择,让你来去选择框选择的选项
http://api.jquery.com/ selected-selector/喜欢 $("select option:selected")

