ajax登录
● Ajax 全称为:“Asynchronous JavaScript and XML”(异步 JavaScript 和 XML), 使用 Ajax,我们可以无刷新状态更新页面,并且实现异步提交,提升了 用户体验。
● Ajax其实质是利用浏览器提供的一个特殊的对象(XMLHttpRequest) 异步地向服务器发送请求,
● 服务器返回部分数据,浏览器让你去利用这些数据对页面做部分的更新, 整个过程,页面无刷新,不打断用户的操作。
out.println(“登录成功”);
/*
out.println(“登录成功”); 响应的内容。就将原来发起请求的页面内容覆盖了
//jsp
*/
//ajax
//解决方案是使用ajax 从前端向后代进行发起请求交互
//如果是ajax方式提交的数据,那么服务器端响应的数据返回后会交给XMLHttpRequest对象
LoginServlet.class
package com.ffyc.webpro.servlet;
import com.ffyc.webpro.dao.LoginDao;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter out =null;
try{
resp.setContentType("text/html;charset=utf-8");
req.setCharacterEncoding("utf-8");
String account=req.getParameter("account");
String password=req.getParameter("password");
LoginDao loginDao=new LoginDao();
boolean b=loginDao.checkLogin(account,password);
out= resp.getWriter();
if(b){
out.println(0);
}else{
out.println(1);
}
}catch (Exception e){
e.printStackTrace();
out.println(2);
}
}
}
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript">
function subform(){
var account=document.getElementById("accountId").value;
var password=document.getElementById("passwordId").value;
var httpObj=new XMLHttpRequest();
httpObj.open("post","login",true)
httpObj.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
httpObj.send("account="+account+"&password="+password);
httpObj.onreadystatechange=function (){
if(httpObj.readyState==4&httpObj.status==200){
if(httpObj.responseText==0){
alert("登录成功");
location.replace("success.html")
}else if(httpObj.responseText==1){
alert("账号或密码错误");
}else{
alert("服务器忙!")
}
}
}
}
</script>
</head>
<body>
<form>
账号<input type="text" name="account" id="accountId"> <br/>
密码<input type="password" name="password" id="passwordId"> <br/>
<input type="button" value="登录" onclick="subform()">
</form>
<a href="register.html">注册</a>
</body>
</html>
success.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
登录成功
</body>
</html>
|