我的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其作为AJAX响应中的数据存储在我的JSP中,并将其内容打印在动态创建的表中?
ArrayList al
尝试使用下面的代码使用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)。