我正在使用maven创建日历网络应用程序,我试图使用JQuery .ajax更新网站而无需重新加载页面。但是我在更新正确的值时遇到了问题。
这是来自servlet的我的doGet方法:
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
int monthChanged = 10;
String action = req.getParameter("action");
String jsp = "/jsp/unischeduleshow.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(jsp);
if(action != null){
monthChanged--;
req.setAttribute("monthChanged", monthChanged);
dispatcher.forward(req, resp);
System.out.println(monthChanged);
}
else{
req.setAttribute("monthChanged", monthChanged);
dispatcher.forward(req, resp);
}
}
这是JSP中的.ajax:
$.ajax({
type: "GET",
data : { action: "backMonth"},
url : "/unischedule",
success: function(){
console.log("${monthChanged}");
}
我也试过这个,但效果相同:
$(document).ready(function(){
$(document).on("click", "#forward", function() {
$.get("/unischedule",{action:"backMonth"}, function(responseText) {
console.log("${monthChanged}");
});
});
});
我简化了代码以更好地显示问题。我试图递减monthChanged
值并按下按钮将其发送到网站。问题是System.out.println("monthChanged");
正在打印递减值,但当我在网站上尝试console.log()
时,它会显示第一个值10
。我试图在很多方面做到这一点,但我找不到解决方案。这个else
块中的第二个调度程序是否会覆盖第一个调度程序?
答案 0 :(得分:0)
您无法通过ajax请求获取servlet属性的值。
我强烈建议您在how to do ajax with servlets
上查看此问题在servlet“unischedule”中,您需要将monthChanged变量写入响应。像这样:
onStop()
现在在你的jsp中,你可以像这样检索响应:
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
int monthChanged = 10;
String action = req.getParameter("action");
String jsp = "/jsp/unischeduleshow.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(jsp);
if(action != null){
monthChanged--;
// req.setAttribute("monthChanged", monthChanged);
// dispatcher.forward(req, resp);
System.out.println(monthChanged);
}
else{
// req.setAttribute("monthChanged", monthChanged);
// dispatcher.forward(req, resp);
}
response.setContentType("text/plain"); // Set content type of the response so that jQuery knows what it can expect.
response.setCharacterEncoding("UTF-8"); // You want world domination, huh?
response.getWriter().write(Integer.toString(monthChanged)); // Write response body.
}