将arraylist从servlet获取到jsp作为ajax响应 [英] Getting arraylist from servlet to jsp as ajax response
本文介绍了将arraylist从servlet获取到jsp作为ajax响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的 Sevlet 中有这个代码
I have this code in my 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 响应中的数据出现并在动态创建的表中打印它的内容?
How do I store this ArrayList al
in my JSP which comes as data in the AJAX response and print it's contents in a dynamically created table?
推荐答案
尝试使用以下代码使用从 servlet 返回的 Json ArrayList 创建动态表.
Try below code to create dynamic table using the Json ArrayList returned from your servlet.
$.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).
It seems like the thing you missed in your code is, you are not appending the created table to any DOM element (DIV).
这篇关于将arraylist从servlet获取到jsp作为ajax响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文