重複の可能性:
サーブレットと 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 を使用して行ったことは、jquery を使用しない場合よりもはるかに簡単でした...
私はAJAXについて何も知りません.これは文字通り初めての作業です(私は学習を始めたばかりです). (または、少なくとも、私が望むことを行うコードを表示してください。おそらく、リバースエンジニアリングできます:))
MoodService は、データベースを処理する私自身のクラスです (どのように機能するかは、この状況には関係ありません。唯一重要なことは、サイトを読み込んだ後にデータをテーブルにリロードする必要があることです)。
助けてくれてありがとう!:)