可能重复:
如何使用 Servlet 和 Ajax?
我有以下代码:
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>
我的问题是:
如何在其中实现 AJAX,以便每 30 秒用新数据刷新表,显示数据库中的最后 25 个条目?我更喜欢使用 jquery,看看到目前为止我用它所做的一切都比没有 jquery 简单得多......
我对 AJAX一无所知,这实际上是我第一次使用它(我刚刚开始学习),所以如果有人能给我一个关于如何做到这一点的分步教程,我将不胜感激。(或者至少告诉我可以做我想做的代码,我可以对它进行逆向工程,可能:))
MoodService 是我自己的处理数据库的类(它如何工作与这种情况无关,唯一重要的是我需要在加载站点后将数据重新加载到表中)。
谢谢您的帮助!:)