将arraylist从servlet转换为jsp作为ajax响应

时间:2014-04-13 16:22:16

标签: ajax json jsp servlets arraylist

我的Sevlet中有这段代码

public class ServletName extends HttpServlet{

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

  PrintWriter out = response.getWriter();
  ArrayList al= new ArrayList<Employee>();
  al = ApproverDao.requestGetter();  
  String json = new Gson().toJson(al);
  response.setContentType("application/json");
  response.setCharacterEncoding("UTF-8");
  out.write(json);
}

这是JSP

<script type="text/javascript">
$(document).ready(function() {
$("#approve_btn").click(function() {
  var remarks =$('[name="result_decide"]').val();
  $.post("/ServletName/decision.do", {result_decide : remarks},
       function(responseJson) {
     var $table = $('<table>').appendTo($('#tabs-4')); 
      $.each(responseJson, function(index, employee) {    
       $('<tr>').appendTo($table)                
         .append($('<td>').text(employee.eName))       
         .append($('<td>').text(employee.fromDate))    
         .append($('<td>').text(employee.toDate));

});
  });
});
</script>

豆子:

class Employee{
private String eName;
private Date fromDate;
private Date toDate;
//setters and getters
}

如何将此ArrayList al存储在我的JSP中,该数据作为AJAX响应中的数据并在动态创建的表中打印出来?

1 个答案:

答案 0 :(得分:1)

尝试下面的代码,使用从servlet返回的Json ArrayList创建动态表。

$.getJSON('/ServletName/decision', function(data) {
    var table = $('<table/>').appendTo($('.adminlist'));
    $('<tr/>').appendTo(table)
              .append($('<th/>').text("Employee Name"))
              .append($('<th/>').text("To Date"))
              .append($('<th/>').text("From Date"));

    data.forEach(function(x, i) {
        var stat = data[i];
        $('<tr/>').appendTo(table)
                  .append($('<td/>').text(stat.eName))
                  .append($('<td/>').text(stat.fromDate))
                  .append($('<td/>').text(stat.toDate));
    });
});

似乎您在代码中遗漏的是,您没有将创建的表追加到任何DOM元素(DIV)。