当用户被重定向到页面时,会话的属性设置为来自服务器的列表......
List<Card> usersCards = DataDAO.getCardsForUser(userAccount);
if(usersCards == null) {
throw new IOException("Card could not be retrieved for this user");
}
session.setAttribute("usersCards",usersCards);
//After successfully logging in send them to the Question page
RequestDispatcher dispatch = getServletContext().getRequestDispatcher("/WEB-INF/QuestionPage.jsp");
dispatch.forward(request,response);
我将该列表保存在jstl变量中......
<c:set var="cardlist" scope="session" value="${sessionScope.usersCards}"></c:set>
<c:set var="cardIndex" scope="session" value="0"></c:set>
单击html按钮我想转到此列表的下一个索引。我认为这可以通过JavaScript实现,一张海报建议在jsp页面上使用隐藏值持有者,如下所示:
<div id="questionCounter">${cardIndex}</div>
然后当我进入我的javascript点击功能时,我对语法感到困惑和困惑。我只想保持此计数器的值,每按一次按钮增加它,然后将文本区域的值更新为该列表的当前索引....
$("#next").click(function() {
var questions = '${cardlist}';
var index = $('#questionCounter').html();
index++;
// here is where I'm stuck...
$('#cardArea').val(questions[index]);
});
答案 0 :(得分:0)
我用ajax完成了这个,以防其他人感到困惑:
$( "#next" ).click(function(){
$.get("QuestionPage", function(responseJSON){
//set the question and category texts
$("#cardArea").val(responseJSON["card"]);
$( "#cat" ).text(responseJSON["category"]);
$( "#cardid" ).text(responseJSON["flashCardnum"]);
//clear answer field after every 'next'...
$( "#answerArea" ).val("");
//set the click function of show button to show the answer..
$( "#show" ).click(function() {
$( "#answerArea" ).val(responseJSON["answer"]);
});
});
});
servlet中的doGet():
//get which user is associated with this browser session...
HttpSession session = request.getSession();
String sessID = session.getId();
UserAccount user = activeUsers.get(sessID);
//get the users cards that are stored within that user object...
List<Card> cards = user.getAllCards();
System.out.println("user "+user.getFirstname()+"has "+cards.size()+" cards.");
//Use the current count to get the right card THEN increment it...
Integer currentCount = (Integer)session.getAttribute("cardCount");
System.out.println("Card Count in doGet(): "+currentCount);
//check that you are not out of cards... if so take them from the top
if(currentCount == (cards.size() - 1)){
currentCount = 0;
}
// get the next card
Card nextCard = cards.get(currentCount);
System.out.println("Next Card: "+nextCard.getCard());
//increment and reset the session attribute...
currentCount++;
session.setAttribute("cardCount", currentCount);
//encode next question as JSON
String json = new Gson().toJson(nextCard);
System.out.println("json coming in ajax: "+json);
//write the next card to the response to be gotten by ajax...
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);