简体   繁体   中英

how to populate the json data in select dropdown using ajax?

Actually i need to display the list of school in a dropdown using select tag so far i am getting the response through hard coded values now here is the problem not able to generate through a link i am getting the data from rest full service how to do that , any on please help

  <html>
   <head> 
<meta http-equiv="content-type" content="application/json; charset=UTF-8">
   </head>
   <body>
     <select id="sel"></select>

     <script>
 $(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));
    });
})
    </script>
   </body>
</html>

You can use the getJSON method of jQuery

$('#brand').change(function(){
   $.getJSON(
     'your url to get json string',
     'get parameters to send if any',
     function(result){
     //result would have your json string 
     //Empty the dropdown if it is having some items
     $('#item').empty();
     //Looping through all the json items
     $.each(result.result, function(){
     //Appending the json items to the dropdown (select tag)
     //item is the id of your select tag
     $('#item').append('<option>'+this['item']+'</option>');
    }); 
   });
});

Try this,

$(document).ready(function(){
      getschool(val);
});

function getschool(val) {
    $.ajax({
        type: "GET",
        url: 'http://localhost:8080/SMWS/Rest/parentService/parent/getSchoolDetails',
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        data:'school_id='+val,
        success: function(data){
            var html = '';
            $.each(data, function(index,value){         
                html+= '<option value="'+value['item_value']+'">'+value['item']+'</option>';
            }); 
           $('#country-list').html(html);
        }
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM