如何使用ajax在select下拉列表中填充json数据

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

本文关键字:填充 json 数据 下拉列表 select 何使用 ajax      更新时间:2023-09-26

实际上,我需要使用select标签在下拉列表中显示学校列表,到目前为止,我正在通过硬编码值获得响应,现在这里是无法通过链接生成的问题,我正在从rest全方位服务中获取数据如何做到这一点,请帮助

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

您可以使用jQuery 的getJSON方法

$('#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>');
    }); 
   });
});

试试这个,

$(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);
        }
    });
}