Ajax
回顾传统的请求:浏览器地址上输入URL、超链接、form表单提交、通过JS代码发送请求
传统请求和特点
- 会刷新页面,产生一个新的页面,未保留页面原有属性
- 页面全部刷新导致了用户的体验变差
- 若服务器中的代码较为复杂,导致用户的体验有空白期。
Ajax请求
-
Ajax是一种技术,多种技术的综合产物
-
Ajax的请求属于异步刷新,刷新页面的一部分,其余部分不会改变
-
故Ajax之间是相互独立的,不会相互影响
Ajax在浏览器当中发送异步请求。请求A和请求B是异步的。类似于多线程并发。
Ajax响应
对于Ajax来说,服务器会给Web前端相应三种数据:普通文本、XML字符串、JSON字符串。
对于浏览器端来说,会通过Ajax进行渲染相应的div部分
Ajax代码属于Web前端的JS代码,和后端的Java无关,后端可以是php语言也可以是c语言。
XMLHttpRequest对象
- XMLhttpRequest对象的方法
方法 | 描述 |
---|---|
abort() | 取消当前请求 |
open(method,url,async,user,psw) | 规定请求method:请求类型GET或POST、url; 文件位置async:true(异步)或false(同步); user:可选的用户名称(用户名和密码是进行身份验证) psw:可选的密码 |
send() | 将请求发送到服务器,用于GET请求 |
send(String) | 将请求发送到服务器,用于POST请求 |
- XMLHttpRequest对象的属性
属性 | 描述 |
---|---|
readyState | 保存XMLHttpRequest的状态。0:请求未初始化 1:服务器连接已建立 2:请求已收到 3:正在处理请求 4:请求已完成且相应已就绪 |
onreadystatechange | 定义当readyState属性发生变化时被调用的函数 |
status | 返回请求的状态号 200:“OK” 400:“Forbidden” 404:“NOT Found” |
responseText | 以字符串返回响应数据 |
发送ajax get请求
前端html代码:
1.第一步:创建AJAX核心对象XMLHttpRequest
var xhr = new XMLHttpRequest();
2.第二步:注册回调函数(当state改变时,此函数会被调用)
xhr.onreadystatechange = function(){ if(this.readyState == 4){ if(this.status == 200){ //获取id操作,将返回的文本放入HTML页面中 } } }
3.第三步:开启通道
xhr.open(“get”, “/ajax/ajaxrequest1”, true)
4.第四步:发送请求
xhr.send()
后端代码:
public class AjaxRequest1Servlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
//创建一个输出流
PrintWriter out = response.getWriter();
out.print("welcome to study ajax!");
}
get请求
通过username=name&usercode=code进行提交。
open改动:
xhr.open("get", "/ajax/ajaxrequest1?username=lisi&usercode=101", true)
post请求
区别:设置请求头(前端代码有区别,后端代码没区别)
//前端改写(顺序是一定的)
xhr.open("post", "/ajax/ajaxrequest1", true)
//模拟AJAX提交from表单?设置请求头的内容类型(模拟表单提交)
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
xhr.send("username=name&password=pwd")
千万要注意这个等于号不能少,要不然无法识别key和value。
//后端
String name = request.getParameter("username");
String password = request.getParameter("password");
案例:使用Ajax POST请求实现用户注册,用户名是否可用
-
在前端,用户输入用户名,失去焦点事件blur发生,然后发送AJax POST请求,提交用户名
-
在后端,接受到用户名,连接数据库,根据用户名去表中搜索
-
如果用户名已存在
- 后端响应消息:用户已存在(在前端页面响应)
-
如果用户名不存在
- 后端相应消息:用户名可以使用(在前端相应)
后端代码
工具类连接数据库
package utils;
import java.sql.*;
public class JDBCUtils {
// 加载驱动,并建立数据库连接(url、username和password根据自身设置修改)
public static Connection getConnection() throws SQLException, ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/jdbc";
String username = "root";
String password = "ww652981";
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
}
pa![请添加图片描述](https://img-blog.csdnimg.cn/bc5e9d3ca0c74a6c9ea797aa87febdcd.png)
ckage com.bjpowernode.ajax;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import utils.JDBCUtils;
@WebServlet(name = "ajaxRequest2", value = "/ajaxRequest2")
public class AjaxRequest2Servlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("userName");
System.out.println(name);
//标记值
boolean flag = false;
ResultSet rs = null;
Connection con = null;
PreparedStatement ps = null;
try {
con = JDBCUtils.getConnection();
String sql = "select id,name from t_user where name = ?";
ps = con.prepareStatement(sql);
ps.setString(1, name);
rs = ps.executeQuery();
if(rs.next()){
flag = true;
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if(rs != null){
try{
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(con != null){
try{
con.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(ps != null){
try{
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
if(!flag){
out.print("<font color='red'>正确输入</font>");
}else{
out.print("<font color='green'>重复输入</font>");
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ajax POST请求验证用户名是否可用</title>
</head>
<body>
<script type="text/javascript">//ajax代码
window.onload = function(){
document.getElementById("userName").onfocus = function(){
document.getElementById("tipMsg").innerHTML = null;
}
//鼠标的光标移动
document.getElementById("userName").onblur = function(){
var xhr = new XMLHttpRequest();
//状态发生变化
xhr.onreadystatechange = function(){
if(this.readyState == 4){
//正常相应
if(this.status == 200){
document.getElementById("tipMsg").innerHTML = this.responseText
}else{
alert(this.status);
}
}
}
//打开通道
xhr.open("POST", "/Ajax/ajaxRequest2", true);
//设置响应头
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//获取表单信息
var username = document.getElementById("userName").value;
//发送信息
xhr.send("userName=" + username);
}
}
</script>
用户名:<input type="text" id="userName"/>
<span id="tipMsg"></span>
</body>
</html>