异步请求四步

1、创建异步请求对象==> let xhr = new XMLHttpRequest();readyState=0

2、给异步对象绑定事件==》xhr.onreadystatechange = function(){}

请求状态码readyState发生改变(除0以外),该函数执行一次

3、初始化异步请求对象==>xhr.open("请求方式","请求路径","true");

readtState=1        true代表使用异步请求的方式

4、发送异步请求==》xhr.send();    readyState=2

获取服务器返回的对象 异步请求状态码readyState = 3

异步请求对象解析服务器返回的数据 异步请求状态码readyState = 4

下面写了一个简单的例子,通过输入用户名,发送异步请求到服务器端,连接数据库进行对比,直接返回用户名密码,适合刚开始练习,注意自己要建数据库,字段名注意与代码中的一致

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ajax-异步请求</title>
<script type="text/javascript">
function doAjax(){
//创建异步请求对象 readyState = 0
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){//异步请求状态码每发生改变,这个事件就会被调用(除0以外)
if(xhr.readyState === 4){
document.getElementById("password").value = xhr.responseText;
}
}
let username = document.getElementById("name").value;
//初始化异步对象 异步请求状态请求状态码readyState = 1 创建通道
//xhr("请求方式","请求路径","true")true代表异步请求
xhr.open("get","/Ajax/query?username=" + username,true);
//异步请求状态码readyState = 2
xhr.send(); //发送请求
//获取服务器返回的对象 异步请求状态码readyState = 3
//异步请求对象解析服务器返回的数据 异步请求状态码readyState = 4
}
</script>
</head>
<body>
<form style="margin-left: 500px; margin-top: 200px">
<label>账号:<input type="text" id="name" placeholder="请输入账号查询密码"/></label><br>
<label>密码:<input type="text" id="password" placeholder="查询的密码在此显示"/></label><br>
<input type="button" value="查询" onclick="doAjax()"/>
</form>
</body>
</html>

controller

@WebServlet(name = "QueryPwdServlet", value = "/query")
public class QueryPwdServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
PrintWriter out = response.getWriter();
try {
conn = DBUtil.getConnection();
String sql = "select username,password from t_login where username = ?";
ps = conn.prepareStatement(sql);
ps.setString(1,username);
rs = ps.executeQuery();
if(rs.next()){
String password = rs.getString("password");
out.println(password);
out.flush();
out.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}