我正在使用Maven创建日历Web应用程序,而我正试图使用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
块中的第二个调度程序是否覆盖第一个?
您无法通过AJAX请求获得Servlet属性的值。
我强烈建议您查看有关如何使用Servlet进行AJAX的问题
在您的servlet" unischedule"中,您需要为响应编写一个月的变量。这样:
@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.
}
现在在JSP中,您可以像这样检索响应:
$(document).on("click", "#forward", function() { // When HTML DOM "click" event is invoked on element with ID "forward", execute the following function...
$.get("../unischedule",{action:"backMonth"}, function(responseText) { // Execute Ajax GET request on URL of "unischedule" and execute the following function with Ajax response text...
console.log(responseText); // your monthChanged value
});
});