使用jQuery,JSON和AJAX来填充下拉 [英] Using jQuery, JSON and AJAX to populate a drop down
问题描述
就像标题所说,我想创建一个下拉使用jQuery,JSON和AJAX的菜单,虽然我熟悉的理论,我还没有付诸实践,任何意见,演示code片段或教程将AP preciated,因为我想下车的最好的开始!
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!
感谢名单提前!
推荐答案
您需要做的$ .getJSON调用来从服务器JSON上document.load或某些其他事件的 http://api.jquery.com/jQuery.getJSON/ 。之后,你必须通过数据环和其附加到你的选择框。看到 http://www.jsfiddle.net/Dyc9Y/1/
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/
<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上面的例子取决于使用JSON格式如下。
offcourse above example depends on json with following format.
{
"0": {"title":"option1", "value":"1"},
"1": {"title":"option2", "value":"2"}
}
编辑:
您还需要熟悉选择框更改事件 http://api.jquery.com/change/和:选择的选择,让你从选择框获取所选的选项
http://api.jquery.com/selected-selector/ 像 $(选择选项:选择)
EDITED:
You also need to be familiar with select box change event http://api.jquery.com/change/ and :selected selector that will allow you to fetch selected option from the selectbox
http://api.jquery.com/selected-selector/ like $("select option:selected")
这篇关于使用jQuery,JSON和AJAX来填充下拉的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!