我需要做一些相当简单的事情:
我有一个 servlet,它获取请求,然后联系数据库,从中获取信息并将其显示为 HTML 表(到目前为止,所有这些都运行良好)。这是 servlet 中的命令:
RequestDispatcher requestDispatcher = req.getRequestDispatcher("index.jsp");
requestDispatcher.forward(req, resp);
index.jsp 是我编写 HTML 和 javascript 来显示数据的地方。
现在,我需要通过 AJAX 每隔 30 秒左右刷新一次数据,这样我就不会重新加载整个页面。另外,我应该在整个操作中使用 jquery。
最简单的方法是什么?我一直在网站上查看一些示例,但我没有设法让它们工作,所以我发布了我自己的问题。我不需要它花哨,我只希望它显示我的表并每 30 秒刷新一次其中的数据(以防有人同时在数据库中放入一些新数据)......
谢谢你们!:)
编辑:
这是整个代码:
public class IndexServlet extends HttpServlet {
MoodService moodService;
public IndexServlet() {
moodService = new MoodService();
}
/**
* Accepts the request and sends it to the dispatcher which takes the database data and presents it as HTML
*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
List<Mood> moodList = moodService.findLastMoods(25); //my way of getting data from database
req.setAttribute("moodList", moodList);
RequestDispatcher requestDispatcher =req.getRequestDispatcher("index.jsp");
requestDispatcher.forward(req, resp);
}
}
和 index.jsp:
<html>
<head>
<title>Previous 25 entries:</title>
<style type="text/css">
#container {width:1200px; margin-left:auto; margin-right: auto;}
#tableheader {width:900px; text-align: center;}
.field {text-align:center; width:300px;}
</style>
</head>
<body style="background-color: black;">
<div id="container">
<table border="1" bordercolor="#FFCC00" width="900" height="80" cellpadding="3" cellspacing="3" style="border-top-left-radius: 15px; border-top-right-radius: 15px; text-align: center; margin-left:auto; margin-right: auto; background-color:#FFFFCC; font-size: 33px; font-family: Monotype Corsiva ">
<tr>
<td style="border-top-left-radius: 10px; border-top-right-radius: 10px;">PREVIOUS 25 ENTRIES:</td>
</tr>
</table>
<%
List<Mood> moodList = (List<Mood>) request.getAttribute("moodList");
for (Mood mood : moodList) {
Integer a = mood.getMoodId();
String moodId = new String();
switch (a) {
case 1:
moodId = "Happy";
break;
case 2:
moodId = "Sad";
break;
case 3:
moodId = "Lonely";
break;
case 4:
moodId = "Angry";
break;
case 5:
moodId = "In Love";
break;
case 6:
moodId = "Content";
break;
} %>
<table id="table" border="1" bordercolor="#FFCC00" width="900" cellpadding="3" cellspacing="3" style="text-align: center; margin-left:auto; margin-right: auto; background-color:#FFFFCC;">
<tr>
<td class="field"> <%=mood.getUserId()%></td>
<td class="field"> <%=moodId%></td>
<%Date date = new Date(mood.getTime());
SimpleDateFormat sdf = new SimpleDateFormat("dd:MM:yyyy hh:mm:ss");
String sDate = sdf.format(date);
%>
<td class="field"> <%=sDate%></td>
</tr>
</table>
<%
}
%>
</div>
</body>
</html>
现在,我希望每 30 秒重新加载整个表格部分(连同可能已放入数据库的新数据)并显示为 html,浏览器可以读取。