JavaWEB-(三十五)Ajax快速入门

本文最后更新于:December 3, 2021 pm

Ajax即Asynchronous Javascript And XML(异步JavaScript和XML)。使用Ajax技术网页应用能够快速地将增量更新呈现在用户界面上,而不需要重载(刷新)整个页面,这使得程序能够更快地回应用户的操作。Ajax 不是一种新的编程语言,而是一种用于创建更好更快以及交互性更强的Web应用程序的技术。Ajax 是一种独立于 Web 服务器软件的浏览器技术。Ajax可使因特网应用程序更小、更快,更友好。

目录

0.原生Ajax

异步对象XMLHttpRequest属性和方法。

1.创建异步对象

1
var xml = new XMLHttpRequest();

2.XMLHttpRequest方法

    1. open(请求方式,服务器端的访问地址,异步还是同步 。

如:

1
xml.open("get", "/StudyAjax01_war_exploded/jsond", true);
    1. send():使用异步对象发送请求。

3.XMLHttpRequest属性

  1. readyState属性:请求的状态
  • 0:表示创建异步对象时,即 new XMLHttpRequest();

  • 1:表示初始异步对象的请求参数。即执行open()方法。

  • 2:使用send()方法发送请求。

  • 3:使用异步对象从服务器接收了数据。

  • 4:异步对象接收了数据,并在异步对象内部处理完成后。

场景剧:你要出门到快递点拿快递。

  1. 你要有出门的准备,穿鞋、穿衣服等等。(0)
  2. 你要出门就必须要看门。(1)
  3. 你到了快递点,问工作人员关于你的快递的情况。(2)
  4. 工作人员把快递给了你,你也拿到了。(3)
  5. 拿着快递回家,并检查。(4)
  1. status属性:网络的状态,和Http的状态码对应
  • 200:请求成功。

  • 404:服务器资源没有找到。

  • 500:服务器内部代码出错。

  1. responseText属性:表示从服务器端返回的数据。
1
var opt = xml.responseText;

4.使用步骤

  1. 创建异步对象
  2. 给异步对象绑定事件。事件名称 onreadystatechange
1
2
3
4
5
xml.onreadystatechange = function () {
if (xml.status == 200 && xml.readyState == 4) {
//执行代码
}
}
  1. 初始请求参数,执行open()函数。
  2. 发送请求,执行send()。

5.完整使用模板

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<script>
function getShowd(){ //getShowd是触发事件函数
// 第一步
var xml = new XMLHttpRequest();
// 第二步
xml.onreadystatechange = function () {
if (xml.status == 200 && xml.readyState == 4) {
var da = xml.responseText;
// 将json格式的字符串转换为json格式的对象
var opt = JSON.parse(da);
document.getElementById("uid").value = opt.id;
//其他执行代码。。。。
}
}

var uid = document.getElementById("uid").value;
var flag = "/StudyAjax01_war_exploded/jsond?id=" + uid;
// 第三步
xml.open("get", flag, true);
// 第四步
xml.send();
}
</script>

<input type="button" onclick="getShowd()" value="查询">

1.全局刷新(Servlet)

1.1 转发

index.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册页面</title>
</head>
<body>
<div align="center" style="margin-top: 60px">
<form action="/StudyAjax01_war_exploded/hs" method="get">
姓名:<input type="text" name="username"> <br><br>
性别:<input type="text" name="sex"> <br><br>
年龄:<input type="text" name="age"> <br><br>
<input type="submit" value="提交">
</form>
</div>
</body>
</html>

dataShow.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<%--
Created by IntelliJ IDEA.
User: dragonone
Date: 2021/11/28
Time: 14:41
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
结果为:${info}
</body>
</html>

📢注意:在使用${}这种时,必须要加上 isELIgnored=”false”。

getDataServlet.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package com.tothefor.controller;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
* @Author DragonOne
* @Date 2021/11/28 12:50
*/
@WebServlet(name = "hee", value = "/hs")
public class getDataServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
String usex = req.getParameter("sex");
String uage = req.getParameter("age");
String info = username + " " + usex + " " + uage;
System.out.println(info);
req.setAttribute("info",info);
req.getRequestDispatcher("/dataShow.jsp").forward(req,resp);
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}

1.2 HttpServletResponse对象

这里只需要index.jsp和getDataServlet.java,其中,index.jsp代码和上面一样,getDataServlet.java的代码有一点点改变:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.tothefor.controller;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
* @Author DragonOne
* @Date 2021/11/28 12:50
*/
@WebServlet(name = "hee", value = "/hs")
public class getDataServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
String usex = req.getParameter("sex");
String uage = req.getParameter("age");
String info = username + " " + usex + " " + uage;
System.out.println(info);
// req.setAttribute("info",info);
// req.getRequestDispatcher("/dataShow.jsp").forward(req,resp);
resp.setContentType("text/html;charset=utf-8");
PrintWriter out = resp.getWriter();
out.println(info);
out.flush();
out.close();
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}

2.局部刷新(Ajax)

使用Ajax的好处就是,不会被表单限制,在其他中也可以使用。

2.1 返回字符串类型

index.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册页面</title>
<script>
function getShowd(){
var xml = new XMLHttpRequest();
xml.onreadystatechange = function () {
if (xml.status == 200 && xml.readyState == 4) {
var da = xml.responseText;
document.getElementById("showda").innerText = da;
}
}

var uname = document.getElementById("name").value;
var usex = document.getElementById("sex").value;
var uage = document.getElementById("age").value;
var flag = "/StudyAjax01_war_exploded/hs?username=" + uname + "&sex=" + usex + "&age=" + uage;
xml.open("get", flag, true);
xml.send();
}
</script>
</head>
<body>
<div align="center" style="margin-top: 60px">
姓名:<input type="text" id="name"> <br><br>
性别:<input type="text" id="sex"> <br><br>
年龄:<input type="text" id="age"> <br><br>
<input type="button" onclick="getShowd()" value="查询">
</div>
<div align="center" style="margin-top: 30px">
<span id="showda">暂无数据。</span>
</div>
</body>
</html>

getDataServlet.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.tothefor.controller;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
* @Author DragonOne
* @Date 2021/11/28 12:50
*/
@WebServlet(name = "hee", value = "/hs")
public class getDataServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
String usex = req.getParameter("sex");
String uage = req.getParameter("age");
String info = username + " " + usex + " " + uage;
System.out.println(info);
resp.setContentType("text/html;charset=utf-8");
PrintWriter out = resp.getWriter();
out.println(info);
out.flush();
out.close();
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}

2.2 返回JSON类型

如果是对象,则需要将对象转化为JSON,再用HttpServletResponse输出。

1
2
3
4
if(ce != null){
ObjectMapper om = new ObjectMapper();
js = om.writeValueAsString(ce);
}

将对象ce转化为String类型的js。

示例

本示例有六个文件:JDBCUtils(工具类)、CityEntiey(实体类)、CityDao(接口)、CityDaoImpl(实现类)、dataShow.jsp(前端页面)、JSONServlet(控制类)。

JDBCUtils.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.tothefor.utils;

import java.sql.*;

/**
* @Author DragonOne
* @Date 2021/11/28 17:12
*/
public class JDBCUtils {
static {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}

//获取连接数据库对象
public static Connection getConnection(){
Connection conn = null;
try {
String url = "jdbc:mysql://localhost:3306/ajaxTest?serverTimezone=GMT%2B8";
String user = "root";
String password = "loong461";
conn = DriverManager.getConnection(url,user,password);
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}

//关闭函数
public static void closeAll(Connection connection, Statement st, ResultSet rs){
try {
if(rs != null){
rs.close();
}
if(st != null){
st.close();
}
if(connection != null){
connection.close();
}

}catch (SQLException e){
e.printStackTrace();
}
}
}

CityEntiey.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package com.tothefor.entity;

import jdk.nashorn.internal.objects.annotations.Getter;
import jdk.nashorn.internal.objects.annotations.Setter;

/**
* @Author DragonOne
* @Date 2021/11/28 17:29
*/

public class CityEntiey {
private int id;
private String name;
private int shenghui;
private String addredd;
private String email;
private String telephone;

@Override
public String toString() {
return "CityEntiey{" +
"id=" + id +
", name='" + name + '\'' +
", shenghui=" + shenghui +
", addredd='" + addredd + '\'' +
", email='" + email + '\'' +
", telephone='" + telephone + '\'' +
'}';
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getShenghui() {
return shenghui;
}

public void setShenghui(int shenghui) {
this.shenghui = shenghui;
}

public String getAddredd() {
return addredd;
}

public void setAddredd(String addredd) {
this.addredd = addredd;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getTelephone() {
return telephone;
}

public void setTelephone(String telephone) {
this.telephone = telephone;
}

public CityEntiey() {
}
}

CityDao
1
2
3
4
5
6
7
8
9
10
11
12
package com.tothefor.dao;

import com.tothefor.entity.CityEntiey;

/**
* @Author DragonOne
* @Date 2021/11/28 17:36
*/
public interface CityDao {
public CityEntiey queryDataByID(int index) throws Exception;
}

CityDaoImpl.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package com.tothefor.dao.impl;

import com.tothefor.dao.CityDao;
import com.tothefor.entity.CityEntiey;
import com.tothefor.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
* @Author DragonOne
* @Date 2021/11/28 17:37
*/
public class CityDaoImpl implements CityDao {
@Override
public CityEntiey queryDataByID(int index) throws Exception{
CityEntiey ce = new CityEntiey();
Connection connection = JDBCUtils.getConnection();
PreparedStatement ps = connection.prepareStatement("select * from city where id=?");
ps.setInt(1,index);
ResultSet rs = ps.executeQuery();
while(rs.next()){
int s1 = rs.getInt(1);
String s2 = rs.getString(2);
int s3 = rs.getInt(3);
String s4 = rs.getString(4);
String s5 = rs.getString(5);
String s6 = rs.getString(6);
ce.setId(s1);
ce.setName(s2);
ce.setShenghui(s3);
ce.setAddredd(s4);
ce.setEmail(s5);
ce.setTelephone(s6);
}
JDBCUtils.closeAll(connection,ps,rs);
return ce;
}
}

dataShow.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<%--
Created by IntelliJ IDEA.
User: dragonone
Date: 2021/11/28
Time: 14:41
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
<script>
function getShowd(){
// console.log("fsas")
var xml = new XMLHttpRequest();
xml.onreadystatechange = function () {
if (xml.status == 200 && xml.readyState == 4) {
var da = xml.responseText;
// 将json格式的字符串转换为json格式的对象
var opt = JSON.parse(da);
document.getElementById("uid").value = opt.id;
document.getElementById("name").value = opt.name;
document.getElementById("sh").value = opt.shenghui;
document.getElementById("address").value = opt.addredd;
document.getElementById("email").value = opt.email;
document.getElementById("tele").value = opt.telephone;
}
}

var uid = document.getElementById("uid").value;
var flag = "/StudyAjax01_war_exploded/jsond?id=" + uid;
xml.open("get", flag, true);
xml.send();
}
</script>
</head>
<body>
<div align="center" style="margin-top: 60px">
ID:<input type="text" id="uid"> <br><br>
姓名:<input type="text" id="name"> <br><br>
省会:<input type="text" id="sh"> <br><br>
地址:<input type="text" id="address"> <br><br>
邮箱:<input type="text" id="email"> <br><br>
电话:<input type="text" id="tele"> <br><br>
<input type="button" onclick="getShowd()" value="查询">
</div>
</body>
</html>

JSONServlet.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.tothefor.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tothefor.dao.CityDao;
import com.tothefor.dao.impl.CityDaoImpl;
import com.tothefor.entity.CityEntiey;
import com.tothefor.utils.JDBCUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
* @Author DragonOne
* @Date 2021/11/28 17:55
*/
@WebServlet(value = "/jsond")
public class JSONServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
int id = Integer.valueOf(req.getParameter("id"));
CityEntiey ce = null;
String js = "无数据";
CityDao cd = new CityDaoImpl();
try {
ce = cd.queryDataByID(id);
}catch (Exception e){
e.printStackTrace();
}
//把对象转换为json,才能通过httpServletResponse输出
if(ce != null){
ObjectMapper om = new ObjectMapper();
js = om.writeValueAsString(ce);
}
System.out.println(js);
//输出json给ajax
resp.setContentType("application/json;charset=utf-8");
PrintWriter out = resp.getWriter();
out.println(js);
out.flush();
out.close();

}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}