目录
目录
1.AJAX-HTTP协议请求报文与响应文本结构
请求报文
行 POST /s?ie=utf-8 HTTP/1.1
头 host: xxx.com
cookie: name=xxx
content-type:application/x-www-form-urlencoded
user-agent: chrome 83
空行
体 username=admin&password=admin
响应报文
行 HTTP/1.1 200 OK
头 Content-type: text/html;charset=utf-8
空行
体 <html>
<head>
</head>
<body>
<h1>体</h1>
</body>
</html>
在chrome查看请求响应报文
请求头:
⭐ 点击view source查看请求行
响应头:
2.node.js下载和使用
1.打开网站nodejs.cn之后选择对应的系统进行下载
安装简单不做赘述
2.检查是否安装完成
打开cmd输入node -v查看
3.express框架下载和使用
1.初始化nodejs
npm init --yes
2.安装express框架
npm i express
⭐安装在项目目录下,否则会报错
3. 创建初始文件简单使用express
//1.引用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端口监听中。。。");
});
⭐释放端口只需要在上图的终端下按ctrl+c即可
4.打开浏览器输入你的ip地址:8000即可查看结果
4.原生ajax简单交互
1.创建get.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: 1px solid rgb(60, 0, 255);
}
</style>
</head>
<body>
<button>点击发送请求</button>
<div id="result">
</div>
</body>
</html>
2.创建server.js文件
//1.引用express
const express = require('express');
//2.创建应用对象
const app = express();
//3.创建路由规则 request, response都是形参 '/server'表示显示在url上的参数
app.get('/server', (request, response) => {
//设置响应头 【设置允许跨域】
response.setHeader('Access-Control-Allow-Origin', '*');
//设置响应
response.send('HELLO AJAX');
});
//4.监听端口启动服务
app.listen(8000, () => {
console.log("服务已经启动,8000端口监听中。。。");
});
3.打开带/server参数的网站
4.响应头显示
5.在html文件添加点击事件查看状态
<script>
//获取button元素
const btn = document.getElementsByTagName('button')[0];
//绑定事件
btn.onclick = function () {
//1.创建对象
const xhr = new XMLHttpRequest();
//2.初始化 设置请求的方法和url
xhr.open('GET', 'http://localhost:8000/server');
//3.发送
xhr.send();
//4.事件绑定
/*
on 当...的时候
readystate 是xhr对象中的一个属性,表示状态 0 1 2 3 4 4表示加载完成可以调用
change改变
*/
xhr.onreadystatechange = function () {
//判断
if (xhr.readyState === 4) {
//判断状态码 只要是两百多就是正常
if (xhr.status >= 200 && xhr.status < 300) {
//处理结果 行 头 空行 体
console.log(xhr.status);//状态码
console.log(xhr.statusText);//状态码字符串
console.log(xhr.getAllResponseHeaders());//所有响应头
console.log(xhr.response);//响应体
}
}
}
}
</script>
在上面判断文档状态和状态码之后--添加代码响应点击之后的事件
//设置result的文本
result.innerHTML = xhr.response;
POST方法
1.创建一个post文件
<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: 1px solid rgb(1, 64, 255);
}
</style>
</head>
<body>
<div id="result">
</div>
<script>
//1.创建元素对象
const result = document.getElementById('result');
//2.绑定事件
result.addEventListener("mouseover", function () {
//1.创建对象
const xhr = new XMLHttpRequest();
//2.初始化 设置类型和url
xhr.open('POST', 'http://localhost:8000/server');
//3.发送
xhr.send();
//4.事件绑定
xhr.onreadystatechange = function () {
//判断
if (xhr.readyState === 4) {
//判断状态码
if (xhr.status >= 200 && xhr.status < 300) {
result.innerHTML = xhr.response;
}
}
}
})
</script>
</body>
</html>
2.在server文件中加上
app.post('/server', (request, response) => {
//设置响应头 【设置允许跨域】
response.setHeader('Access-Control-Allow-Origin', '*');
//设置响应体
response.send('HELLO AJAX post');
});
注意:加完之后要重启端口
3.传递参数给服务器部分形式
⭐参数可以任意形式,只要服务端可以对数据进行处理
//3.发送
// xhr.send('a=100&b=200&c=300');
xhr.send('a:100&b:200&c:300');
请求头设置
在open方法之后输入
4.1预定义请求头
//设置请求头
xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
4.2自定义请求头
xhr.setRequestHeader('name', 'zhougongjin');
出现错误!!!
解决方法1:在后端中设置响应头
//设置响应头,防止自定义请求头出错
response.setHeader('Access-Control-Allow-Headers', '*');
解决方法2:直接接受全部的请求方法
app.all('/server', (request, response) => {
//设置响应头 【设置允许跨域】
response.setHeader('Access-Control-Allow-Origin', '*');
//设置响应头,防止自定义请求头出错
response.setHeader('Access-Control-Allow-Headers', '*');
//设置响应体
response.send('HELLO AJAX post');
});
JSON响应
简易版:
app.all('/json-server', (request, response) => {
//设置响应头 【设置允许跨域】
response.setHeader('Access-Control-Allow-Origin', '*');
//响应一个数据
const data = {
name: 'zhougongjin'
}
//对象字符串转换
let str = JSON.stringify(data);
//设置响应头,防止自定义请求头出错
//response.setHeader('Access-Control-Allow-Headers', '*');
//设置响应体
response.send(str);
});
进阶版:
1.手动对数据进行处理
<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: 1px solid rgb(1, 64, 255);
}
</style>
</head>
<body>
<div id="result"></div>
<script>
//创建对象
const result = document.getElementById('result');
//绑定事件
window.onkeydown = function () {
//发送请求
const xhr = new XMLHttpRequest();
//初始化
xhr.open('GET', 'http://localhost:8000/json-server');
//发送
xhr.send();
//事件绑定
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
//手动转换
let data = JSON.parse(xhr.response);
result.innerHTML = data.name;
}
}
}
}
</script>
</body>
</html>
2.自动数据转换
<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: 1px solid rgb(1, 64, 255);
}
</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://localhost: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.name;
}
}
}
}
</script>
</body>
</html>
5.nodemon自动重启工具安装
在终端输入
npm install -g nodemon
启动方式
nodemon 文件名.js
6.IE缓存问题
服务端数据改变,IE进行了本地缓存,没能实现数据的实时变化
解决方法:
//发送请求
xhr.open('GET', 'http://localhost:8000/ie?t=' + Date.now());
通过获取当前事件的时间戳,实时获取数据
修改serve.js文件
//针对ie缓存
app.get('/ie', (request, response) => {
//设置响应头 【设置允许跨域】
response.setHeader('Access-Control-Allow-Origin', '*');
//设置响应体
response.send('HELLO IE');
});
7.延时和网络异常
超时处理回调函数
serve.js模拟延时效果:
//延时响应
app.get('/delay', (request, response) => {
//设置响应头 【设置允许跨域】
response.setHeader('Access-Control-Allow-Origin', '*');
//设置延时
setTimeout(() => {
//设置响应体
response.send('延时响应');
}, 3000)
});
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: 1px solid #0509ee;
}
</style>
</head>
<body>
<button>点击发送请求</button>
<div id="result"></div>
<script>
//创建对象
const btn = document.getElementsByTagName('button')[0];
const result = document.getElementById('result');
//点击事件
// btn.onclick = function () {
btn.addEventListener('click', function () {
//创建新对象
const xhr = new XMLHttpRequest();
//超时设置2s之后取消请求
xhr.timeout = 2000;
//超时回调
xhr.ontimeout = function () {
alert("网络异常,请稍后重试!!")
}
//网络异常回调
xhr.onerror = function () {
alert("你的网络不可用,请检查之后再访问!!")
}
//发送请求
xhr.open('GET', 'http://localhost: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>
网络异常模拟要使用chrome的调试:
效果:
8.手动取消请求
html代码实现【引用了上一节的delay】
<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 xhr = null;
btns[0].onclick = function () {
xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost:8000/delay');
xhr.send();
}
btns[1].onclick = function () {
xhr.abort();
}
</script>
</body>
</html>
9.重复请求
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>
<script>
//获取元素对象
const btns = document.querySelectorAll('button');
let xhr = null;
//标识变量
let issending = false; // 是否正在发送AJAX请求
btns[0].onclick = function () {
//判断标识变量
if (issending) { xhr.abort() };
xhr = new XMLHttpRequest();
//修改标识变量值
issending = true;
xhr.open('GET', 'http://localhost:8000/delay');
xhr.send();
//文档状态为4的时候
xhr.onreadystatechange = function () {
if (xhr.readystate === 4) {
//修改标识变量值
issending = false;
}
}
}
</script>
</body>
</html>
10.jquary中的ajax请求
在serve.js中设置一个all请求
//JQUARY中ajax请求
app.all('/jquary-server', (request, response) => {
//设置响应头 【设置允许跨域】
response.setHeader('Access-Control-Allow-Origin', '*');
const data = { name: '周公瑾' };
//设置响应体
// response.send('HELLO jquary ajax');
response.send(JSON.stringify(data));
});
创建一个jquary-ajax请求.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">
<link crossorigin="anonymous" href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css"
rel="stylesheet">
<script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<title>JQUARY-AJAX请求应用</title>
</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://localhost:8000/jquary-server', { a: 100, b: 200 }, function (data) {
console.log(data);
}, 'json');
})
$('button').eq(1).click(function () {
$.post('http://localhost:8000/jquary-server', { a: 100, b: 200 }, function (data) {
console.log(data);
});
})
</script>
</body>
</html>
在服务端转换数据之后在前端定义数据显示类型的差异
GET直接把参数显示在url上,POST要在payload中查看
⭐jquary中通用请求方法
$('button').eq(2).click(function () {
$.ajax({
//url
url: 'http://localhost:8000/jquary-server',
//参数
data: { a: 100, b: 200 },
//请求类型
type: 'GET',
//成功之后回调
success: function (data) {
console.log(data);
}
}
);
})
<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">
<link crossorigin="anonymous" href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css"
rel="stylesheet">
<script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<title>JQUARY-AJAX请求应用</title>
</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://localhost:8000/jquary-server', { a: 100, b: 200 }, function (data) {
console.log(data);
}, 'json');
})
$('button').eq(1).click(function () {
$.post('http://localhost:8000/jquary-server', { a: 100, b: 200 }, function (data) {
console.log(data);
});
})
$('button').eq(2).click(function () {
$.ajax({
//url
// 超时测试
// url: 'http://localhost:8000/delay',
url: 'http://localhost:8000/jquary-server',
//参数
data: { a: 100, b: 200 },
//请求类型
type: 'GET',
//响应体结果
dataType: 'json',
//成功之后回调
success: function (data) {
console.log(data);
},
//超时时间
timeout: 2000,
//失败的回调
error: function () {
console.log('出错拉!!!');
}
}
);
})
</script>
</body>
</html>
AXIOS中的请求方法
<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">
<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.0.0-alpha.1/axios.js"></script>
<title>axios发送请求</title>
</head>
<body>
<button>GET</button><button>POST</button><button>AJAX</button>
<script>
const btns = document.querySelectorAll('button');
//配置baseurl
axios.defaults.baseURL = 'http://localhost:8000';
//点击事件绑定
btns[0].onclick = function () {
//get请求
axios.get('/axios-server', {
//url参数
params: {
id: 100,
vip: 10
},
//请求头信息
Headers: {
name: '周公瑾',
age: 20
}
}).then(value => {
console.log(value);
})
}
</script>
</body>
</html>
//axios
app.all('/axios-server', (request, response) => {
//设置响应头 【设置允许跨域】
response.setHeader('Access-Control-Allow-Origin', '*');
const data = { name: '周公瑾' };
//设置响应体
// response.send('HELLO jquary ajax');
response.send(JSON.stringify(data));
});