jQuery:迭代ajax响应列表并在下拉列表中填充它

时间:2014-08-23 18:02:38

标签: jquery ajax

来自servlet的JSON响应为

empID: rajuM, givenName: Raju M, empID: rajuM01, givenName: Raju M R

我想迭代这个列表并在下拉列表中填充它。我尽我所能去做但没有运气请帮助。请看下面的代码。

$('#select').change(function(){
    var dept = $('select[name="select-dept"] option:selected').text();
    console.log(dept);
    $.ajax({
        type: "GET",
        url: "updateEmployeeServlet",
        data: {dept: dept},
        success: function(list){
        $('#employee-list').html("Please select Employee under Department:      <select name = \"employee\"></select>");

            $.each(list, function(index, data){
                $('#employee-list select').html("<option value = "+data.empID+">"+data.givenName+"</option>");
            });
        },
        error: function(){
            alert("something went wrong");
        }
    });
});

2 个答案:

答案 0 :(得分:1)

我认为你只想要追加而不是html

$('#employee-list select').append("<option value = "+data.empID+">"+data.givenName+"</option>");

答案 1 :(得分:1)

你可以这样做:

  

首先你需要数据对象,如: [{'empID':'rajuM','givenName':'Raju M'},{'empID':'rajuM01','givenName':'Raju M R “}]

success: function(list)
{
  $('#employee-list').html("Please select Employee under Department:<select name =\"employee\"></select>");
  var options = "";
  for(i in list)
  {
     options += "<option value = "+list[i].empID+">"+list[i].givenName+"</option>"; 
  }
  $('#employee-list select').append(options);
}

Here是小提琴。