当我点击锚点
时,这个问题与前一个问题有关<a href="#" id="Email">send email</a>
它使用json调用servlet
$("#Email").click(function() {
var option={
"action":"sendEmail"
};
$.getJSON('StudentManagementServlet',option, function(hasEmail) {
if(hasEmail == false){
// //view form to let user enter his email
$("#CommViaEmail").fadeIn("normal");
}
});
});
在servlet中我处理请求
if (action != null && action.equals("sendEmail")) {
//open connection to db
con.setAutoCommit(false);
String email = ParentManagement.getParentEmail(con, stdNo);
if (email != null) {
String commResult = createAccountAndSendEmail(con, parentNo, email);
request.setAttribute("result", commResult);
request.setAttribute("incp", "ResultPage");
RequestDispatcher dispatcher = request.getRequestDispatcher("/index.jsp");
dispatcher.forward(request, response); //doesn't make forward!!!!!
System.out.println(">>send email DONE!!");
con.commit();
return;
} else {
boolean hasEmail = false;
String json = new Gson().toJson(hasEmail);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
}
这里的问题是,如果用户有电子邮件,那么我发送电子邮件但请求不要转发到结果页面,即使是打印的语句“System.out.println(”&gt;&gt;发送电子邮件完成! ! “);” ??
答案 0 :(得分:1)
你需要让JS / jQuery完成这项工作。让servlet将true
写为JSON结果,并在JS中执行
if (hasEmail) {
window.location = 'index.jsp';
} else {
$("#CommViaEmail").fadeIn("normal"); //view form to let user enter his email
}
或者当您想自己控制URL时,将新位置添加到JSON
Map<String, Object> data = new HashMap<String, Object>();
data.put("hasEmail", true);
data.put("location", "index.jsp");
// ...
与
..., function(data) {
if (data.hasEmail) {
window.location = data.location;
} else {
$("#CommViaEmail").fadeIn("normal"); //view form to let user enter his email
}
}
答案 1 :(得分:0)
您正在从客户端发出AJAX请求,并尝试在服务器端“转发”该请求。
AJAX请求 DONT 刷新页面。 javascript函数中的hasEmail
变量将是包含index.jsp
的HTML的字符串。