Ajax学习笔记
1.Ajax特点:
优点:
- 无需刷新页面即可与服务器端通信
- 允许根据用户事件更新部分页面内容
缺点
- 没有浏览历史,不可回退
- 存在跨域问题
- SEO(搜索引擎优化)不友好——爬虫不可爬取Ajax请求得来的数据
2.http协议:
(hypertext transport protocol)超文本传输协议,规定浏览器和万维网服务器之间互相通信的规则。
请求报文
样例格式:
请求行 GET/s?ie=utf-8 HTTP/1.1 //格式:请求类型(GET\POST)+url路径+http协议版本
请求头 Host:atguigu.com
Cookie:name=guigu
Content-type:application/x-www-form-urlencoded
User-Agent:chrome 83
请求空行 //必须有
请求体 username=admin&password=admin //如果是get请求,请求体为空;如果是post请求,可空可不空
响应报文
样例格式:
响应行 HTTP/1.1 200 OK //HTTP协议版本+响应状态码+响应状态字符串
响应头 Content-Type:text/html;charset=utf-8
Content-length: 2048
Content-encoding: gzip
响应空行 //必须有
响应体 <html> //响应主要内容
<head>
</head>
<body>
<h1>xxx</h1>
</body>
</html>
3.原生AJAX
3.1 express的基本使用
//引入express
const { request, response } = require('express');
const express = require('express');
//2.创建应用对象
const app = express();
//3.创建路由规则
//request 是对请求报文的封装
//response 是对响应报文的封装
app.get('/',(request,response)=>{
//设置响应
response.send('HELLO EXPRESS');
});
//4.监听端口启动服务
app.listen(8000,()=>{
console.log("服务已经启动,8000端口监听中....")
})
通过node.js启动可以在localhost:8000访问
3.2 Ajax发送GET请求
前端部分:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AJAX GET 请求</title>
<style>
#result{
width: 200px;
height: 100px;
border: solid 1px #90b;
}
</style>
</head>
<body>
<button>点击发送请求</button>
<div id="result"></div>
<script>
//获取button元素
const btn = document.getElementsByTagName('button')[0];
const result = document.getElementById("result");
//绑定事件
btn.onclick = function(){
//1.创建对象
const xhr = new XMLHttpRequest();
//2.初始化 设置请求方法和 url
xhr.open('GET','http://127.0.0.1:8000/server?a=100&b=200&c=300');
//3.发送
xhr.send();
//4.事件绑定
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
//判断响应状态码 2xx都是成功
if(xhr.status >= 200 && xhr.status < 400)
{
//处理结果
//响应行
console.log(xhr.status); //状态码
console.log(xhr.statusText); //状态字符串
console.log(xhr.getAllResponseHeaders());
console.log(xhr.response); //响应体
//设置result的文本
result.innerHTML = xhr.response;
}else{
}
}
}
}
</script>
</body>
</html>
服务器部分:
//引入express
const { request, response } = require('express');
const express = require('express');
//2.创建应用对象
const app = express();
//3.创建路由规则
//request 是对请求报文的封装
//response 是对响应报文的封装
app.get('/server', (request, response) => {
//设置响应头 设置允许跨域
response.setHeader('Access-Control-Allow-Origin', '*');
//设置响应体
response.send('HELLO AJAX');
});
app.listen(8000, () => {
console.log("服务已经启动,8000端口监听中....")
})
传参方法or格式:
在url后加问号 参数赋值之间用&连接
ex: xhr.open('GET','http://127.0.0.1:8000/server?a=100&b=200&c=300');
3.3 Ajax发送post请求
前端部分:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AJAX POST 请求</title>
<style>
#result{
width: 200px;
height: 100px;
border: solid 1px #90b;
}
</style>
</head>
<body>
<div id="result"></div>
<script>
//获取元素对象
const result = document.getElementById("result");
//绑定事件
result.addEventListener("mouseover",function(){
//1.创建对象
const xhr = new XMLHttpRequest();
//2.初始化 设置类型与URL
xhr.open('POST','http://127.0.0.1:8000/server');
//设置请求头
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.setRequestHeader('name','atguigu');
//3.发送
xhr.send('a=100&b=200&c=300');
//4.事件绑定
xhr.onreadystatechange = function(){
//判断
if(xhr.readyState === 4){
if(xhr.status >= 200 && xhr.status < 300){
result.innerHTML = xhr.response;
}
}
}
})
</script>
</body>
</html>
服务器部分:
//引入express
const { request, response } = require('express');
const express = require('express');
//2.创建应用对象
const app = express();
//3.创建路由规则
//request 是对请求报文的封装
//response 是对响应报文的封装
app.all('/server', (request, response) => {
//设置响应头 设置允许跨域
response.setHeader('Access-Control-Allow-Origin', '*');
//响应头
response.setHeader('Access-Control-Allow-Headers', '*');
//设置响应体
response.send('HELLO AJAX POST');
});
//4.监听端口启动服务
app.listen(8000, () => {
console.log("服务已经启动,8000端口监听中....")
})
post请求体参数设置
设置位置
设置在xhr.send()参数内
设置格式
‘a=100&b=200&c=300’
ex:xhr.send('a=100&b=200&c=300');
在网页中查看位置
设置请求头
专用方法
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
参数
接收两个参数,头的名字和头的值,同样可以在network中查看
3.4 服务器端响应json数据
前端部分:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JSON响应</title>
<style>
#result {
width: 200px;
height: 100px;
border: solid 1px #90b;
}
</style>
</head>
<body>
<div id="result"></div>
<script>
const result = document.getElementById('result');
//绑定键盘按下事件
window.onkeydown = function(){
//发送请求
const xhr = new XMLHttpRequest();
//设置响应体数据的类型
xhr.responseType = 'json' ;
//初始化
xhr.open('GET','http://127.0.0.1:8000/json-server');
//发送
xhr.send();
//事件绑定
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status >= 200 && xhr.status < 300){
// console.log(xhr.response);
// result.innerHTML = xhr.response;
//手动
// let data = JSON.parse(xhr.response);
// console.log(data);
//result.innerHTML = data.name;
//自动转换
console.log(xhr.response);
result.innerHTML = xhr.response.name;
}
}
}
}
</script>
</body>
</html>
服务器部分:
//引入express
const { request, response } = require('express');
const express = require('express');
//2.创建应用对象
const app = express();
app.all('/json-server', (request, response) => {
//设置响应头 设置允许跨域
response.setHeader('Access-Control-Allow-Origin', '*');
//响应头
response.setHeader('Access-Control-Allow-Headers', '*');
//响应一个数据
const data = {
name: 'atguigu'
};
//对对象进行字符串转换
let str = JSON.stringify(data);
//设置响应体
response.send(str);
});
//4.监听端口启动服务
app.listen(8000, () => {
console.log("服务已经启动,8000端口监听中....")
})
3.5 IE缓存问题
问题
IE缓存开启之后,会对ajax的数据进行缓存,有时会导致页面不能及时更新
解决办法
在url路径最后加时间戳,就不会走缓存路线
ex:xhr.open("GET",'http://127.0.0.1:8000/ie?t='+Date.now());
全部代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>IE缓存问题</title>
<style>
#result {
width: 200px;
height: 100px;
border: solid 1px #90b;
}
</style>
</head>
<body>
<button>点击发送请求</button>
<div id="result"></div>
<script>
const btn = document.getElementsByTagName('button')[0];
const result = document.querySelector('#result');
btn.addEventListener('click',function(){
const xhr = new XMLHttpRequest();
xhr.open("GET",'http://127.0.0.1:8000/ie?t='+Date.now());
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if (xhr.status >= 200 && xhr.status < 300){
result.innerHTML = xhr.response ;
}
}
}
})
</script>
</body>
</html>
3.6 Ajax请求超时与网络异常处理
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>请求超时与网络异常</title>
<style>
#result {
width: 200px;
height: 100px;
border: solid 1px #90b;
}
</style>
</head>
<body>
<button>点击发送请求</button>
<div id="result"></div>
<script>
const btn = document.getElementsByTagName('button')[0];
const result = document.querySelector('#result');
btn.addEventListener('click', function () {
const xhr = new XMLHttpRequest();
//超时设置 2s 设置
xhr.timeout = 2000;
//超时回调
xhr.ontimeout = function (){
alert("网络异常,请稍后重试");
}
//网络异常 回调
xhr.onerror - function (){
alert("你的网络似乎出了一些问题");
}
xhr.open("GET", 'http://127.0.0.1:8000/delay');
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
result.innerHTML = xhr.response;
}
}
}
})
</script>
</body>
</html>
3.7 Ajax取消请求
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>取消请求</title>
</head>
<body>
<button>点击发送</button>
<button>点击取消</button>
<script>
//获取元素对象
const btns = document.querySelectorAll('button');
let x = null;
btns[0].onclick = function(){
x = new XMLHttpRequest();
x.open("GET",'http://127.0.0.1:8000/delay');
x.send();
}
//abort
btns[1].onclick = function(){
x.abort();
}
</script>
</body>
</html>
3.8 解决重复请求问题
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>重复请求问题</title>
</head>
<body>
<button>点击发送</button>
<!-- <button>点击取消</button> -->
<script>
//获取元素对象
const btns = document.querySelectorAll('button');
let x = null;
//标识变量
let isSending = false;// 正在发送AJAX请求
btns[0].onclick = function () {
//判断标识变量
if (isSending) x.abort();//如果正在发送则取消前一个
x = new XMLHttpRequest();
//修改 标识变量的值
isSending = true;
x.open("GET", 'http://127.0.0.1:8000/delay');
x.send();
x.onreadystatechange = function () {
if (x.readyState === 4) {
//修改标识变量
isSending = false;
}
}
}
//abort
btns[1].onclick = function () {
x.abort();
}
</script>
</body>
</html>
4.jquery中的Ajax
jquery发送Ajax请求
第一个参数为url地址
第二个参数是一个对象,为参数设置
第三个参数为回调函数
第四个参数为响应体类型,可不填,也可以填json
前端部分:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jquery 发送AJAX请求</title>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css">
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<h2 class="page-header">jQuery发送AJAX请求</h2>
<button class="btn btn-primary">GET</button>
<button class="btn btn-danger">POST</button>
<button class="btn btn-info">通用性方法ajax</button>
</div>
<script>
$('button').eq(0).click(function(){
$.get('http://127.0.0.1:8000/jquery-server',{a:100,b:200},function(data){
console.log(data);
},'json')
})
$('button').eq(1).click(function () {
$.post('http://127.0.0.1:8000/jquery-server', { a: 100, b: 200 }, function (data) {
console.log(data);
})
})
$('button').eq(2).click(function () {
$.ajax({
//url
url: 'http://127.0.0.1:8000/jquery-server',
//参数设置
data: {a: 200,b:200},
//请求类型
type:'GET',
//响应体结果
dataType:'json',
//成功的回调
success: function(data){
console.log(data);
},
//超时时间
timeout: 2000,
//失败的回调
error: function(){
console.log('出错啦!!');
},
//头信息的设置
headers: {
c:300,
d:400
}
})
})
</script>
</body>
</html>
后端部分:
//jquery 服务
app.all('/jquery-server', (request, response) => {
//设置响应头 设置允许跨域
response.setHeader('Access-Control-Allow-Origin', '*');
response.setHeader('Access-Control-Allow-Headers', '*');
//response.send('Hello jQuery AJAX');
const data = {name:'尚硅谷'};
response.send(JSON.stringify(data));
});
5.axios
5.1 get/post/通用方法
get:第一个参数为url地址,第二个为其他参数配置的对象
post:第一个参数为url地址,第二个为请求体,第三个为其他参数配置
通用方法:参数只有一个对象,参数顺序与报文顺序一致
前端部分
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>axios 发送ajax请求</title>
<script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.js"></script>
</head>
<body>
<button>GET</button>
<button>POST</button>
<button>AJAX</button>
<script>
const btns = document.querySelectorAll('button');
//配置 baseURL
axios.defaults.baseURL = 'http://127.0.0.1:8000';
btns[0].onclick = function(){
//GET 请求
axios.get('/axios-server', {
//url 参数
params: {
id:100,
vip:7
},
//请求头信息
headers :{
name:'atguigu',
age:20
}
}).then(value => {
console.log(value);
});
}
btns[1].onclick = function () {
//POST 请求
axios.post('/axios-server',
{
username:'admin',
password:'admin'
} ,{
//url 参数
params: {
id: 200,
vip: 9
},
//请求头信息
headers: {
height: 100,
weight: 100,
}
}
)}
btns[2].onclick = function(){
axios({
//请求方法
method: 'POST',
//url
url: '/axios-server',
//url参数
params: {
vip:10,
level:30
},
headers: {
a:100,
b:200
},
//请求体参数
data:{
username:'admin',
password:'admin'
}
}).then(response=>{
console.log(response);
//响应状态码
console.log(response.status);
//响应状态字符串
console.log(response.statusText);
//响应头信息
console.log(response.headers);
//响应体
console.log(response.data);
})
}
</script>
</body>
</html>
后端部分:
//axios
app.all('/axios-server', (request, response) => {
//设置响应头 设置允许跨域
response.setHeader('Access-Control-Allow-Origin', '*');
//响应头
response.setHeader('Access-Control-Allow-Headers', '*');
//对对象进行字符串转换
const data = {name:'尚硅谷'};
//设置响应体
response.send(JSON.stringify(data));
});
5.2使用fetch函数发送Ajax请求:
前端部分:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>fetch 发送 AJAX请求</title>
</head>
<body>
<button>AJAX请求</button>
<script>
const btn = document.querySelector('button');
btn.onclick = function(){
fetch('http://127.0.0.1:8000/fetch-server?vip=10',{
//请求方法
method: 'POST',
//请求头
headers:{
name: 'atguigu'
},
//请求体
body:'username=admin&password=admin'
}).then(response =>{
return response.text();
}).then(response=>{
console.log(response);
});
}
</script>
</body>
</html>
后端部分:
//fetch 服务
app.all('/fetch-server', (request, response) => {
//设置响应头 设置允许跨域
response.setHeader('Access-Control-Allow-Origin', '*');
//响应头
response.setHeader('Access-Control-Allow-Headers', '*');
//对对象进行字符串转换
const data = { name: '尚硅谷' };
//设置响应体
response.send(JSON.stringify(data));
});
6.跨域
6.1 同源策略
同源:协议,域名,端口号 必须完全相同。
违背同源策略就是跨域。
6.2 解决跨域问题
JSONP
JSONP是什么
JSONP(JSON with Padding)是非官方的跨域解决方案,只支持get请求。
JSONP工作原理
网页中有一些标签天生有跨域能力 exp:img link iframe script
JSONP 就是利用script 标签的跨域能力来发送请求
JSONP 的实现原理
ajax响应返回结果是函数调用,而函数的实参就是我们想给客户端返回的结果数据,并且函数必须提前声明。
前端部分
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>原理</title>
<style>
#result{
width: 300px;
height: 100px;
border: solid 1px #78a;
}
</style>
</head>
<body>
<div id="result"></div>
<script>
//处理数据
function handle(data) {
//获取result元素
const result = document.getElementById('result');
result.innerHTML = data.name;
}
</script>
<!-- <script src="http://127.0.0.1:5500/%E8%B7%A8%E5%9F%9F/JSONP/js/app.js"></script> -->
<script src="http://127.0.0.1:8000/jsonp-server"></script>
</body>
</html>
服务器部分:
//JSONP服务
app.all('/jsonp-server',(request,response)=>{
// response.send('console.log("hello jsonp-server")');
const data = {
name: '尚硅谷'
};
console.log(data);
//转字符串
let str = JSON.stringify(data);
//返回结果
response.end(`handle(${str})`);
});
6.3 原生jsonp实践
模拟功能:检测用户名是否存在(直接返回用户名不存在)
思路就是往文件里加script标签
前端部分:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>案例</title>
</head>
<body>
用户名:<input type="text" id="username">
<p></p>
<script>
//获取input元素
const input = document.querySelector('input');
const p = document.querySelector('p');
//声明handle函数
function handle(data){
input.style.border = "solid 1px #f00";
//修改P标签的提示文本
p.innerHTML = data.msg;
}
//绑定事件
input.onblur = function (){
//读取用户的输入值
let username = this.value;
//向服务器端发送请求,检测用户名是否存在
//1.创建 script 标签
const script = document.createElement('script');
//2.设置标签的 src 属性
script.src = 'http://127.0.0.1:8000/check-username';
//3.将script 插入到文档中
document.body.appendChild(script);
}
</script>
</body>
</html>
服务器部分:
//用户名检测是否存在
app.all('/check-username', (request, response) => {
// response.send('console.log("hello jsonp-server")');
const data = {
exist:1,
msg: '用户名已经存在'
};
//转字符串
let str = JSON.stringify(data);
//返回结果
response.end(`handle(${str})`);
});
6.3 jquery发送jsonp请求
url地址后必须加上一个 ?callback=? (固定格式),之后jquery会自动在callback之后加上一串字符,将作为函数名在后端使用
前端部分:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Jquery-jsonp</title>
<style>
#result{
width: 300px;
height: 100px;
border: solid 1px #089;
}
</style>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<button>点击发送jsonp请求</button>
<div id="result">
</div>
<script>
$('button').eq(0).click(function(){
$.getJSON('http://127.0.0.1:8000/jquery-jsonp-server?callback=?',function(data){
$('#result').html(`
名称: ${data.name},
校区: ${data.city}
`)
})
})
</script>
</body>
</html>
后端部分
后端接受callback参数,并发送回前端页面,jquery会处理并返回data值
app.all('/jquery-jsonp-server', (request, response) => {
// response.send('console.log("hello jsonp-server")');
const data = {
name: 'sangng',
city: ['beijing','shganai']
};
//转字符串
let str = JSON.stringify(data);
//接受 callback 参数
let cb = request.query.callback;
//返回结果
response.end(`${cb}(${str})`);
});
6.4 CORS响应头实现跨域
特点
不需要客户端做任何操作,完全在服务器中进行处理,支持get和post请求
用法
在服务端设置响应头允许跨域
前端部分:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CORS</title>
<style>
#result{
width: 200px;
height: 100px;
border: solid 1px #90b;
}
</style>
</head>
<body>
<button>发送请求</button>
<div id="result"></div>
<script>
const btn = document.querySelector('button');
btn.onclick = function(){
//1.创建对象
const x = new XMLHttpRequest();
//2. 初始化设置
x.open("GET","http://127.0.0.1:8000/cors-server");
//3.发送
x.send();
//4.绑定事件
x.onreadystatechange = function(){
if(x.readyState === 4){
if(x.status >= 200 && x.status <300){
//输出响应体
console.log(x.response);
}
}
}
}
</script>
</body>
</html>
后端部分:
app.all('/cors-server',(request,response)=>{
//设置响应头
response.setHeader("Access-Control-Allow-Origin","*");//*指所有网页 也可换成某个特指的网页
response.send('hello CORS');
})