一、什么是Ajax:
AJAX = Asynchronous JavaScript and XML(异步的 JavaScript 和 XML)。
AJAX 不是新的编程语言,而是一种使用现有标准的新方法。
AJAX 最大的优点是在不重新加载整个页面的情况下,可以与服务器交换数据并更新部分网页内容。
AJAX 不需要任何浏览器插件,但需要用户允许 JavaScript 在浏览器上执行。XMLHttpRequest 只是实现 Ajax 的一种方式。AJAX 是一种用于创建快速动态网页的技术。
通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
传统的网页(不使用 AJAX)如果需要更新内容,必需重载整个网页面。
在 2005 年,Google 通过其 Google Suggest 使 AJAX 变得流行起来。Google Suggest 使用 AJAX 创造出动态性极强的 web 界面:当您在谷歌的搜索框输入关键字时,JavaScript 会把这些字符发送到服务器,然后服务器会返回一个搜索建议的列表。
二、Ajax的主要优点包括:
- 提高用户体验:页面无需重新加载即可更新内容,使得用户界面更加流畅。
- 减少服务器负载:只请求需要的数据,而不是整个页面,减少了数据传输量。
- 分离数据和表示:后端可以专注于数据的处理和生成,前端则负责数据的展示。
三、在pom文件添加依赖:
<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version> 1.2.70</version> </dependency>
四、Ajax的简单创建过程:
1.//创建对象 let xmlHttpRequest = new XMLHttpRequest();
2.//配置向后端请求类型 get post 异步请求(get和post的方式不同) xmlHttpRequest.open("get","/webApp_war_exploded/ajax1",true);
3.//监听数据是否请求成功 xmlHttpRequest.onreadystatechange=function (){
}
4.//发送请求 xmlHttpRequest.send();(非常重要)
5.// 服务端和客户端握手 if (xmlHttpRequest.readyState==4){
//当页面属于正常运行的时候
if (xmlHttpRequest.status==200){
// 获取后端的数据存入其中
let Text = xmlHttpRequest.responseText;
//数据渲染前端页面 document.getElementById("show").innerHTML=Text;//可以自行定义属于js部分
} }
6.创建相应的Ajax类,可以使用httpservlet,servlet等都可以
7.// 后端产生数据,返回前端,同时设置编码,否则前端页面会成为乱码
8.// 返回数据 PrintWriter writer = resp.getWriter();
五、使用Ajax实现前后端分离的测试代码:
测试代码一:
在添加servlet和tomcat的环境中才可以进行此代码的测试
前端代码:
创建前端页面时创建HTML,并且如果在一个包下面,在同一站点访问时,应该先写上包名再写上文件名称
xmlHttpRequest.open("get","/webApp_war_exploded/ajax1",true);注意这句中要和你所创建的Java类中的@WebServlet("/ajax1")的名称相同,否则并不产生实际效果
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title><script>function ajax1(){//创建对象let xmlHttpRequest = new XMLHttpRequest();//配置向后端请求类型 get post 异步请求xmlHttpRequest.open("get","/webApp_war_exploded/ajax1",true);//监听数据是否请求成功xmlHttpRequest.onreadystatechange=function (){// 服务端和客户端握手if (xmlHttpRequest.readyState==4){if (xmlHttpRequest.status==200){// 获取后端的数据存入其中let Text = xmlHttpRequest.responseText;//数据渲染前端页面document.getElementById("show").innerHTML=Text;}}}//发送请求xmlHttpRequest.send();}</script>
</head>
<body>
<div id="show">数据内容</div><button onclick="ajax1()">点击</button>
</body>
</html>
Java类代码:
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;
@WebServlet("/ajax1")
public class ajax1 extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {this.doPost(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 后端产生数据,返回前端resp.setContentType("text/html;charset=utf-8");
// 返回数据PrintWriter writer = resp.getWriter();writer.write("来自后端数据");}
}
在访问时:有包的话先写包名
六、Ajax的get请求方式:
前端代码:
xmlHttpRequest.open("get","/webApp_war_exploded/ajax2?name="+user+"&pas="+pwd,true);这句中let后面的内容则与其对应,但是等于前面可以自定义名称,在编写后端代码时,则与名称对应,其他注意的点和步骤则于前面相同
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>ajax get方式传值</title><script>function ajax2(){//获取表单数据let user = document.querySelector(".user").value;let pwd = document.querySelector(".pwd").value;//创建ajax对象let xmlHttpRequest = new XMLHttpRequest();//配置向后端请求类型 get post 异步请求xmlHttpRequest.open("get","/webApp_war_exploded/ajax2?name="+user+"&pas="+pwd,true);//监听数据是否请求成功xmlHttpRequest.onreadystatechange=function (){// 服务端和客户端握手if (xmlHttpRequest.readyState==4){if (xmlHttpRequest.status==200){// 获取后端的数据存入其中let Text = xmlHttpRequest.responseText;//数据渲染前端页面document.getElementById("show").innerHTML=Text;}}}//发送请求xmlHttpRequest.send();}</script>
</head>
<body>
<div id="show" style="border: solid 5px black;width: 300px;height: 300px;">
<!-- 获得的数据-->
</div>
姓名<input type="text" class="user"><br>
密码<input type="password" class="pwd"><br>
<button onclick="ajax2()">提交</button>
</body>
</html>
后端代码:
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;@WebServlet("/ajax2")
public class ajax2 extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {this.doPost(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 后端产生数据,返回前端req.setCharacterEncoding("utf-8");resp.setContentType("text/html;charset=utf-8");
// 返回数据//接受传递过来的姓名和密码String user = req.getParameter("name");String pwd = req.getParameter("pas");// 返回数据PrintWriter writer = resp.getWriter();writer.write("来自后端数据"+user);writer.write("来自后端数据"+pwd);}
}
七、Ajax的Post请求方式:
前端代码:
xmlHttpRequest.open("post","/webApp_war_exploded/ajax2",true);与get方式不同,注意,post还需要加上这句,否则传值失败,为空
xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>ajax post方式传值</title><script>function ajax3(){//获取表单数据let user = document.querySelector(".user").value;let pwd = document.querySelector(".pwd").value;//创建ajax对象let xmlHttpRequest = new XMLHttpRequest();//配置向后端请求类型 post 异步请求xmlHttpRequest.open("post","/webApp_war_exploded/ajax2",true);//监听数据是否请求成功xmlHttpRequest.onreadystatechange=function (){// 服务端和客户端握手if (xmlHttpRequest.readyState==4){if (xmlHttpRequest.status==200){// 获取后端的数据存入其中let Text = xmlHttpRequest.responseText;//数据渲染前端页面document.getElementById("show").innerHTML=Text;}}}xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");//发送请求xmlHttpRequest.send("name="+user+"&pas="+pwd);}</script>
</head>
<body>
<div id="show" style="border: solid 5px black;width: 300px;height: 300px;">
<!-- 获得的数据-->
</div>
姓名<input type="text" class="user"><br>
密码<input type="password" class="pwd"><br>
<button onclick="ajax3()">提交</button>
</body>
</html>
后端代码与get方式相同,并且从此中就可以对比看出两种请求方式的不同;
八、Ajax的实例应用:(AJAX JSON 实例)
前端代码:
其中一定要与javaBean字段对应
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>ajax get方式传值</title><style>span{font-size: 20px;}</style><script>function ajax4(){//创建ajax对象let xmlHttpRequest = new XMLHttpRequest();//配置向后端请求类型 get post 异步请求xmlHttpRequest.open("get","/webApp_war_exploded/ajax3",true);//监听数据是否请求成功xmlHttpRequest.onreadystatechange=function (){// 服务端和客户端握手if (xmlHttpRequest.readyState==4){if (xmlHttpRequest.status==200){// 获取后端的数据存入其中let Text = JSON.parse(xmlHttpRequest.responseText);//把json格式的字符串转换成json格式的对象,数据渲染前端页document.querySelector(".id").innerHTML = Text[0].id;document.querySelector(".name").innerHTML = Text[0].name;document.querySelector(".sex").innerHTML = Text[0].sex;document.querySelector(".age").innerHTML = Text[0].age;document.querySelector(".major").innerHTML = Text[0].major;document.querySelector(".time").innerHTML = Text[0].time;// document.getElementById("show").innerHTML=Text;}}}//发送请求xmlHttpRequest.send();}</script>
</head>
<body onload="ajax4()">
<div id="show" style="border: solid 5px black;width: 500px;height: 500px;">
<!-- 获得的数据-->
//第一步
<!--id<span class="id"></span>-->
<!--姓名<span class="name"></span>-->
<!--性别<span class="sex"></span>-->
<!--年龄<span class="age"></span>-->
<!--专业<span class="major"></span>-->
<!--时间<span class="time"></span>--><table><tr><th>id</th><th>姓名</th><th>性别</th><th>年龄</th><th>专业</th><th>时间</th><th>操作一</th><th>操作二</th></tr>
//第二步<tr><td class="id"></td><td class="name"></td><td class="sex"></td><td class="age"></td><td class="major"></td><td class="time"></td></tr></table>
</div>
</body>
</html>
第一步的后端代码:
第一步是先将数据写死,并没用有和数据库连接
import Dao.StudentDao;
import Model.Student;
import Model.Students;
import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;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.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;@WebServlet("/ajax3")
public class ajax3 extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {this.doPost(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {ArrayList<Student> sts = new ArrayList<>();Student s1 = new Student();Student s2 = new Student();Student s3 = new Student();s1.setId(1);s1.setName("aa");s1.setSex("ss");s1.setAge(22);s1.setMajor("dd");s1.setTime("ww");s2.setId(1);s2.setName("aa");s2.setSex("ss");s2.setAge(22);s2.setMajor("dd");s2.setTime("ww");s3.setId(1);s3.setName("aa");s3.setSex("ss");s3.setAge(22);s3.setMajor("dd");s3.setTime("ww");sts.add(s1);sts.add(s2);sts.add(s3);String s = JSON.toJSONString(sts);System.out.println("s = " + s);resp.setContentType("application/json");// 后端产生数据,返回前端req.setCharacterEncoding("utf-8");//响应用户请求,告知编码resp.setContentType("text/html;charset=utf-8");PrintWriter writer = resp.getWriter();writer.write(s);//释放资源和对象writer.flush();writer.close();
第二步的后端代码:
第二步是先将数据写死,并和数据库连接(采用的mybatis的注解方式):
接口代码:
import Dao.StudentDao;
import Model.Student;
import Model.Students;
import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;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.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;@WebServlet("/ajax3")
public class ajax3 extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {this.doPost(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {InputStream on = Resources.getResourceAsStream("config/mybatis_config.xml");SqlSessionFactory build1 = new SqlSessionFactoryBuilder().build(on);SqlSession sqlSession1 = build1.openSession();StudentDao studentDao1 = sqlSession1.getMapper(StudentDao.class);List<Students> all = studentDao1.findAll();req.setAttribute("all",all);String s = JSON.toJSONString(all);System.out.println("s = " + s);resp.setContentType("application/json");// 后端产生数据,返回前端req.setCharacterEncoding("utf-8");//响应用户请求,告知编码resp.setContentType("text/html;charset=utf-8");PrintWriter writer = resp.getWriter();writer.write(s);//释放资源和对象writer.flush();writer.close();}
}
九、实战:
(此项目的增加,更新,删除,只有前端可以使用和数据库没有连接)
(1)在同一数据库创建表:
代码:
-- 创建表
CREATE TABLE students (
id INT PRIMARY KEY,
name VARCHAR(50),
sex VARCHAR(10),
age INT,
tel BIGINT,
scores DECIMAL(5,2),
school VARCHAR(100)
);
-- 插入数据
INSERT INTO students (id, name, sex, age, tel, scores, school) VALUES
(1, 'aa', '男', 19, 18292743385, 98.3, '清华大学'),
(2, 'bb', '男', 19, 15292743385, 88.3, '清华大学'),
(3, 'cc', '女', 20, 15292743385, 90.0, '清华大学'),
(4, 'dd', '男', 17, 16292743385, 80.0, '清华大学'),
(5, 'ee', '女', 19, 15392743385, 78.3, '西安文理'),
(6, 'ff', '男', 29, 13292743385, 68.3, '西安文理'),
(7, 'uu', '男', 29, 17292743385, 88.8, '宝鸡文理1'),
(8, 'cc1', '男', 19, 19292743385, 98.3, '宝鸡文理'),
(9, 'cc2', '男', 19, 28292743385, 78.3, '宝鸡文理'),
(10, 'cc3', '男', 19, 18292743385, 68.3, '宝鸡文理'),
(11, 'cc4', '男', 19, 18292743385, 78.3, '宝鸡文理'),
(12, 'cc3', '男', 19, 18292743385, 68.3, '宝鸡文理'),
(13, 'cc4', '男', 19, 18292743385, 78.3, '宝鸡文理'),
(14, 'cc3', '男', 19, 18292743385, 68.3, '宝鸡文理'),
(15, 'cc4', '男', 19, 18292743385, 78.3, '宝鸡文理');
(2)创建javaBean:
(3)前端代码:
HTML:
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><link rel="stylesheet" href="showlist.css"><script>let data;window.onload = function () {ajax4();function ajax4() {//创建ajax对象let xmlHttpRequest = new XMLHttpRequest();//配置向后端请求类型 get post 异步请求xmlHttpRequest.open("get", "/webApp_war_exploded/ajax3", true);//监听数据是否请求成功xmlHttpRequest.onreadystatechange = function () {// 服务端和客户端握手if (xmlHttpRequest.readyState == 4) {if (xmlHttpRequest.status == 200) {// 获取后端的数据存入其中data= JSON.parse(xmlHttpRequest.responseText);init();//把json格式的字符串转换成json格式的对象,数据渲染前端页// document.getElementById("show").innerHTML=Text;}}}//发送请求xmlHttpRequest.send();}var pos;let tab = document.getElementById("tab");var update1 = document.querySelector(".update");var add1 = document.querySelector(".add");//1.渲染数据function init() {
//1.逐条遍历数据for (let index = 0; index < data.length; index++) {//2.生成一行trlet tr = document.createElement("tr")if (index % 2 == 0) {tr.style.backgroundColor = "lightgreen";}//3.生成行内的tdfor (let j = 0; j < 7 + 2; j++) {let td = document.createElement("td")tr.appendChild(td);//添加到tr}
//4,给每一行的td赋初值tr.children[0].innerHTML = data[index].id;tr.children[1].innerHTML = data[index].name;tr.children[2].innerHTML = data[index].sex;tr.children[3].innerHTML = data[index].age;tr.children[4].innerHTML = data[index].tel;tr.children[5].innerHTML = data[index].scores;tr.children[6].innerHTML = data[index].school;
//5.创建操作按钮let button = document.createElement("button")let button1 = document.createElement("button")button.innerHTML = "删除";button1.innerHTML = "更新";
//2.删除数据button.onclick = del(index);button1.onclick = update(index);
//6.添加按钮对象tr.children[7].appendChild(button)tr.children[8].appendChild(button1)tab.appendChild(tr);}}//点击按钮实现,删除操作function del(index) {//想想,为啥这么写?好处是啥return function () {if (window.confirm("你确定要删除吗?")) {data.splice(index, 1);tab.innerHTML = "";init();}}}//点击按钮,实现数据回显效果function update(index) {//想想,为啥这么写?好处是啥return function () {var update = document.querySelector(".update");var add = document.querySelector(".add");
// update.style.display = "none";
// add.style.display = "block";
// data[data.length-1].id+1;document.querySelector(".xm1").value = data[index].name
// document.querySelectorAll(".xb1")[0].checked?"男":"女";document.querySelector(".nl1").value = data[index].age;document.querySelector(".dh1").value = data[index].tel;document.querySelector(".cj1").value = data[index].scoresdocument.querySelector(".xx1").value = data[index].schoolpos = index;//记录更新的数组下标}}//3.数据添加let sub = document.getElementById("sub")sub.onclick = function () {let id = data[data.length - 1].id + 1;let xm = document.querySelector(".xm").valuelet xb = document.querySelectorAll(".xb")[0].checked ? "男" : "女";let nl = document.querySelector(".nl").valuelet dh = document.querySelector(".dh").valuelet cj = document.querySelector(".cj").valuelet xx = document.querySelector(".xx").value
//数据入库let newobj = {"id": id,"name": xm,"sex": xb,"age": nl,"tel": dh,"scores": cj,"school": xx}data.push(newobj);//数据添加仓库之后,重新渲染界面tab.innerHTML = "";add1.reset();init();//调用init方法重新渲染界面}//4实现更新let sub1 = document.getElementById("sub1")sub1.onclick = function () {let id = data[data.length - 1].id + 1;let xm = document.querySelector(".xm1").valuelet xb = document.querySelectorAll(".xb1")[0].checked ? "男" : "女";let nl = document.querySelector(".nl1").valuelet dh = document.querySelector(".dh1").valuelet cj = document.querySelector(".cj1").valuelet xx = document.querySelector(".xx1").value
//更新这条数据data[pos] = {"id": id,"name": xm,"sex": xb,"age": nl,"tel": dh,"scores": cj,"school": xx}update1.reset();tab.innerHTML = "";init();//调用init方法重新渲染界面}}</script>
</head><body>
<h1 class="title">学生数据展示</h1>
<div id="box"><div class="form"><form action="" class="update">姓名<input type="text" class="xm1" placeholder="请输入更新姓名"><br>性别<input type="radio" class="xb1" value="男" name="sex" checked>男<input type="radio" value="男" class="xb1" name="sex">女<br>年龄<input type="text" placeholder="请输入年龄" class="nl1"><br>电话<input type="text" class="dh1"><br>成绩<input type="text" class="cj1"><br>学校<input type="text" class="xx1"><br><input type="button" id="sub1" value="更新"></form><form action="" class="add">姓名<input type="text" class="xm" placeholder="请输入姓名"><br>性别<input type="radio" class="xb" value="男" name="sex" checked>男<input type="radio" value="男" class="xb" name="sex">女<br>年龄<input type="text" placeholder="请输入年龄" class="nl"><br>电话<input type="text" class="dh"><br>成绩<input type="text" class="cj"><br>学校<input type="text" class="xx"><br><input type="button" id="sub" value="添加"></form></div><div class="show"><table><thead><tr><th>ID</th><th>姓名</th><th>性别</th><th>年龄</th><th>电话</th><th>成绩</th><th>学校</th><th>操作1</th><th>操作2</th></tr></thead><tbody id="tab"></tbody></table></div>
</div></body></html>
(4)css:
*{margin:0;padding:0;
}
table{/* 表格中的双线合成单线 */border-collapse:collapse;width: 900px;margin: 0 auto;}
th,td{border: solid 1px red;
}
#box{width: 1300px;margin:30px auto;}
.form{float:left;}
.form input{margin:10px;
}
.show{float: right;
}
.title{text-align: center;margin:20px;font-size: 50px;background:lightgray;}
(5)后端代码:
接口代码:
(6)后端Java类代码:
import Dao.StudentDao;
import Model.Student;
import Model.Students;
import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;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.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;@WebServlet("/ajax3")
public class ajax3 extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {this.doPost(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {InputStream on = Resources.getResourceAsStream("config/mybatis_config.xml");SqlSessionFactory build1 = new SqlSessionFactoryBuilder().build(on);SqlSession sqlSession1 = build1.openSession();StudentDao studentDao1 = sqlSession1.getMapper(StudentDao.class);List<Students> all = studentDao1.findAll1();req.setAttribute("all",all);String s = JSON.toJSONString(all);System.out.println("s = " + s);resp.setContentType("application/json");// 后端产生数据,返回前端req.setCharacterEncoding("utf-8");//响应用户请求,告知编码resp.setContentType("text/html;charset=utf-8");PrintWriter writer = resp.getWriter();writer.write(s);//释放资源和对象writer.flush();writer.close();}
}