Using jQuery, JSON and AJAX to populate a drop down

后端 未结 2 721
长情又很酷
长情又很酷 2021-01-22 21:33

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, d

2条回答
  •  南笙
    南笙 (楼主)
    2021-01-22 21:55

    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/

    
    
    $(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("");
            for(key in json)
                $("#fillME").append("");
       });    
     });
    });
    

    offcourse above example depends on json with following format.

    { 
       "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 selector that will allow you to fetch selected option from the selectbox http://api.jquery.com/selected-selector/ like $("select option:selected")

提交回复
热议问题