1、什么是Ajax
Ajax(Asynchronous JavaScript and XML)是一种用于创建动态网页应用的技术,允许网页在不重新加载整个页面的情况下与服务器进行异步交互。
2、组成部分
1.JavaScript: 用于实现网页的动态行为和与服务器的异步通信。
2.XMLHttpRequest: 这是 Ajax 的核心,允许浏览器向服务器发送请求并接收响应。虽然名称中包含 XML,但实际上它可以处理多种格式的数据(如 JSON、HTML、纯文本等)。
3.DOM(文档对象模型): 用于动态更新网页内容,更新用户在浏览器中看到的内容。
4.服务器: 处理来自客户端的请求,返回数据,这些数据通常是 JSON 或 XML 格式。
3、工作原理
1.用户事件: 用户在网页上执行某个动作(例如点击按钮)。
2.发送请求: JavaScript 使用 XMLHttpRequest 对象发送到服务器的请求。
3.处理请求: 服务器接收请求并处理,根据请求返回相应的数据。
4.接收响应: JavaScript 接收服务器的响应。
5.更新界面: 使用 DOM 操作更新网页上的内容,而无需重新加载整个页面。
4、优点
1.提高用户体验: 用户可以在无需刷新整个页面的情况下,与应用程序进行交互,从而提高响应速度和用户体验。
2.节省带宽: 只传输必要的数据,而不是整个网页。
3.动态内容加载: 可以根据用户的操作或输入,动态加载数据。
5、缺点
1.搜索引擎优化问题: Ajax 内容可能不被搜索引擎很好地索引,导致 SEO 难题。
2.复杂性: 开发和调试 Ajax 应用程序可能较复杂,尤其是在处理多个异步请求时。
3.浏览器兼容性: 虽然大多数现代浏览器都支持 Ajax,但在一些早期版本的浏览器中可能会存在兼容性问题。
6、JavaScript 原生 AJAX
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript 原生 AJAX</title>
<script>
window.onload = function(){//文档加载完成后执行
//获取文本域元素
let textarea = document.getElementById("textarea");
//需求1:点击按钮1,通过 GET 请求获取数据
let btn1 = document.getElementById("btn1");
//绑定按钮1事件
btn1.onclick = function(){
//1.创建 XMLHttpRequest 对象
let xhr = new XMLHttpRequest();
//2.初始化,设置请求方式和 url
xhr.open("GET", "http://127.0.0.1:8000/helloWorld");
//设置请求头信息(可以设置自定义请求头信息)
//xhr.setRequestHeader("Content-Type","text/plain;charset=UTF-8");
xhr.setRequestHeader("token","token123");//自定义会话的 token
//3.发送请求
xhr.send();
//4.事件绑定,处理服务器返回的结果。readyState 是 xhr 对象中的属性,表示状态有:0、1、2、3、4
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
//判断响应状态码:一般200开头的都是成功
/*
xhr.status:响应状态码
xhr.statusText:状态字符串
xhr.getAllResponseHeaders():所有响应头
xhr.response:响应体
*/
if(xhr.status >= 200 && xhr.status < 300){
//设置 textarea 的文本
textarea.innerHTML = xhr.response;
}
}
}
}
//需求2:点击按钮2,通过 POST 请求获取数据
let btn2 = document.getElementById("btn2");
btn2.onclick = function(){
let xhr = new XMLHttpRequest();
xhr.open("POST", "http://127.0.0.1:8000/say");
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.status >= 200 && xhr.status < 300){
//设置 textarea 的文本
textarea.innerHTML = xhr.response;
}
}
}
}
</script>
</head>
<body>
<button id="btn1">按钮1 通过 GET 请求获取数据</button>
<button id="btn2">按钮2 通过 POST 请求获取数据</button>
<br><br>
<textarea id="textarea" cols="30" rows="10"></textarea>
</body>
</html>
7、jQuery 发送 AJAX 请求
jQuery 发送 AJAX 请求主要有 3 个常用方法
1、$.get()
2、$.post()
3、$.ajax()
其中,$.get() 和 $.post() 都是简单的请求方式,有 4 个参数:url,[data],[callback],[type]
url:请求的 url 地址
data:参数值(键值对格式)
callback:成功时的回调函数
type:返回的数据格式,xml, html, script, json, text, _default
$.ajax() 用于处理比较复杂的请求,它可以设置很多参数,比如:头部信息(headers,注意值不允许包含中文或者说是全角输入法的内容)、成功的回调(success)、失败的回调(error)、超时设置(timeout)等
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery 发送 AJAX</title>
<!-- 通过 CDN 引入 js库 -->
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.js"></script>
<script>
$(function () {//文档加载完成后执行
//发送 get 请求
$("#btn1").click(function () {
//get 请求有4个参数:url、参数(键值对)、回调函数、返回的数据类型
$.get("http://127.0.0.1:8000/getById", { id: 1 }, function (data) {
const userName = data.userName;
const introduction = data.introduction;
//在文本域中显示信息
$("#textarea").val("用户名:" + userName + ",自我介绍:" + introduction);
}, "json");
});
//发送 post 请求
$("#btn2").click(function () {
//post 请求也有4个参数:url、参数(键值对)、回调函数、返回的数据类型
$.post("http://127.0.0.1:8000/getByName", { "userName": "周星驰" }, function (data) {
const userName = data.userName;
const introduction = data.introduction;
//在文本域中显示信息
$("#textarea").val("用户名:" + userName + ",自我介绍:" + introduction);
}, "json");
});
//发送 ajax 请求。语法:jQuery.ajax(url,[settings])
$("#btn3").click(function () {
const myToken = "your token message";
const otherHeader = "can no be Chinese!";
$.ajax({
//url 地址
url: "http://127.0.0.1:8000/getByName",
//请求类型
type: "POST",
//头部信息(值不允许包含中文)
headers: {
token: myToken,
other: otherHeader
},
//参数
data: { "userName": "海明威" },
//响应体结果
dataType: "json",
//成功的回调
success: function (data) {
const userName = data.userName;
const introduction = data.introduction;
//在文本域中显示信息
$("#textarea").val("用户名:" + userName + ",自我介绍:" + introduction);
},
//失败的回调
error: function () {
$("#textarea").val("接口调用失败啦!");
},
//超时时间设置,单位:毫秒
timeout: 2000,
})
});
})
</script>
</head>
<body>
<h2>jQuery 发送 AJAX 请求</h2>
<button id="btn1">GET 请求</button>
<button id="btn2">POST 请求</button>
<button id="btn3">通用型方法 ajax</button>
<br><br>
<textarea id="textarea" cols="30" rows="10"></textarea>
</body>
</html>
8、axios 发送 AJAX 请求
axios 是现在前端比较流行和热门的 AJAX 工具库,也是 VUE 和 React 推荐的发送 AJAX 请求的工具。
axios 发送 AJAX 请求主要有 3 个常用方法(与 jQuery 类似):
1、axios.get()
2、axios.post()
3、axios()
axios 在调用 AJAX 有一个 then() 函数用来接收返回数据
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>axios 发送 AJAX</title>
<!-- 通过 CDN 引入 js库 -->
<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.5.0/axios.js"></script>
<script>
window.onload = function () {//文档加载完成后执行
//获取文本域元素
let textarea = document.getElementById("textarea");
//获取按钮
let btn1 = document.getElementById("btn1");
let btn2 = document.getElementById("btn2");
let btn3 = document.getElementById("btn3");
//配置 axios 基础请求路径
axios.defaults.baseURL = "http://127.0.0.1:8000";
//发送 get 请求
btn1.onclick = function () {
axios.get("/getById",
//参数
{
params: {
id: 1
},
//请求头信息
headers: {
token: "your token"
}
}
).then(response => {
//响应状态码
console.log(response.status);
//响应状态字符串
console.log(response.statusText);
//响应头信息
console.log(response.headers);
//响应体
console.log(response.data);
//在文本域显示信息
const userName = response.data.userName;
const introduction = response.data.introduction;
textarea.innerHTML = "用户名:" + userName + ",自我介绍:" + introduction;
}).catch(function (error) {
console.log(error);
});
};
//发送 post 请求
btn2.onclick = function () {
axios.post("/getByName",
//请求体参数
{
userName: "周星驰"
},
//其它参数
{
params: {
otherParam: "other"
},
//请求头参数
headers: {
//注意:后台服务该 POST 方法获取 userName 参数的格式是:@RequestParam String userName,需要增加头部 Content-Type 的配置
"Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
"token": "your token"
}
}
).then(function (response) {
//响应状态码
console.log(response.status);
//响应状态字符串
console.log(response.statusText);
//响应头信息
console.log(response.headers);
//响应体
console.log(response.data);
//在文本域显示信息
const userName = response.data.userName;
const introduction = response.data.introduction;
textarea.innerHTML = "用户名:" + userName + ",自我介绍:" + introduction;
}).catch(function (error) {
console.log(error);
});
};
//发送 axios 请求
btn3.onclick = function () {
axios({
//请求方法
method: "POST",
//url
url: "/getByName",
//url参数
params: {
otherParam: "other"
},
//头信息
headers: {
//注意:后台服务该 POST 方法获取 userName 参数的格式是:@RequestParam String userName,需要增加头部 Content-Type 的配置
"Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
"token": "your token"
},
//请求体参数
data: {
userName: "海明威"
}
}).then(response => {
//响应状态码
console.log(response.status);
//响应状态字符串
console.log(response.statusText);
//响应头信息
console.log(response.headers);
//响应体
console.log(response.data);
//在文本域显示信息
const userName = response.data.userName;
const introduction = response.data.introduction;
textarea.innerHTML = "用户名:" + userName + ",自我介绍:" + introduction;
}).catch(function (error) {
console.log(error);
});
}
}
</script>
</head>
<body>
<h2>axios 发送 AJAX 请求</h2>
<button id="btn1">GET 请求</button>
<button id="btn2">POST 请求</button>
<button id="btn3">通用型方法 axios</button>
<br><br>
<textarea id="textarea" cols="30" rows="10"></textarea>
</body>
</html>