如何根据Servlet返回结果加载对应HTML,操作response返回值异常如何解决
问题修复方案
你无法操作data、页面加载逻辑不生效的核心原因有2个:
- Servlet 输出使用了
out.println()方法,会自动在返回内容末尾追加换行符,前端拿到的实际是"Studente\n"/"Docente\n",和你代码里的字符串恒等判断条件匹配失败 - 前端JS代码存在无效语句
entById("response").value;,会导致JS运行中断
具体修复步骤
后端修改(推荐)
把Servlet里的输出方法换成out.print(),去掉多余的换行符,也可以直接返回JSON格式提升扩展性:
@WebServlet(name = "validateServlet", value = "/validate-servlet") public class ValidateServlet extends HttpServlet { private DAO model = null; public void init(ServletConfig conf) throws ServletException { super.init(conf); ServletContext ctx = conf.getServletContext(); String url = ctx.getInitParameter("DB-URL"); String user = ctx.getInitParameter("user"); String pwd = ctx.getInitParameter("pwd"); model = new DAO(url,user,pwd); } public void destroy(){} public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { // 如果用JSON返回可以改成application/json类型 response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); Persona user = DAO.Validate(request.getParameter("mail"),request.getParameter("passwd")); if(user!=null) { HttpSession s = request.getSession(); s.setAttribute("Nome",user.getNome()); s.setAttribute("Cognome",user.getCognome()); s.setAttribute("Ruolo",user.getType()); s.setAttribute("account",request.getParameter("mail")); s.setAttribute("psw",request.getParameter("passwd")); // 把println改成print,去掉换行符 out.print(user.getType()); } else { // 同样把println改成print out.print("NOT IN DB"); } out.flush(); } }
前端修改
首先删除无效的entById("response").value;语句,然后对返回的data做去空白处理再判断,如果需要操作加载完成的HTML页面内的元素,要写在load方法的回调函数中:
<!DOCTYPE html> <html lang="en"> <head> <title>Pagina di identificazione</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <h2>Identificazione utente</h2> <form method="post"> <p> Login: <input id="mail" type="text" name="login" value=""/> </p> <p>Password: <input id="pass" type="password" name="passwd"/></p> <p><input id="login" type="button" name="submit" value="login"/></p> </form> <div id="risposta" class="outputTextArea"></div> <div id="insert" class="outputTextArea"></div> <script type="text/javascript"> $(document).ready(function(){ $("#login").click(function (){ const account = document.getElementById("mail").value; const password = document.getElementById("pass").value; $.post("validate-servlet",{mail: account,passwd: password}, function (data){ // 先去除返回值首尾的空白字符再判断 const res = data.trim(); if(res ==="Studente") { $("#insert").load("student.html", function() { // 这里可以操作student.html加载完成后的页面元素 }); } else if(res ==="Docente") { $("#insert").load("insert.html", function() { // 这里可以操作insert.html加载完成后的页面元素 }); } else if(res === "NOT IN DB") { $("#risposta").html("账号或密码错误"); } }); }); }); </script> </body> </html>
内容的提问来源于stack exchange,提问作者Matteo Pagliarello
相关产品推荐
相关产品推荐

