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

时间:2015-12-16 11:55:54

标签: javascript jquery json ajax

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

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

3 个答案:

答案 0 :(得分:0)

您可以使用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>');
    }); 
   });
});

答案 1 :(得分:0)

试试这个,

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

答案 2 :(得分:-2)

    function getschool(val) {
    type: "POST",
    url: 'http://localhost:8080/SMWS/Rest/parentService/parent/getSchoolDetails',
contentType: "application/json;charset=utf-8",
dataType: "jsonp",
data:'school_id='+val,
success: function (msg) {
             //alert("Success " + msg.d);


             $('#yourselectname').empty().append($("<option></option>").val(0).html("Select"));
             if (msg.d.length > 0) {
                 for (var i = 0; i < msg.d.length; i++) {
                     $(ddl).append($("<option></option>").val(msg.d[i].ItemId).html(msg.d[i].ItemName));
                 }
             }
         },
         failure: function (respose) {
             alert(respose.d);
         }

     });
 }