原生Ajax
所有操作都以注释的形式写在实例代码中
重启工具nodemon安装
在测试的时候,我们需要频繁更改服务端代码,但是每次更改都需要重启一次过于麻烦,所以我们借助nodemon工具实现自动重启。
安装方法:在终端输入 npm install -g nodemon
使用方法:nodemon js文件
如果报错:可以参考这个
服务端代码
以下所有例子都使用这一个服务端代码
// 1. 引入express
const { 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 EXPRESS-2');
});
// all表示可以接受任意类型的请求
app.all('/json-server',(request,response)=>{
// 设置响应头,设置允许跨域
response.setHeader('Access-Control-Allow-Origin',"*");
// 响应头,表示所有类型的请求头都能接受
response.setHeader('Access-Control-Allow-Headers','*')
// 响应一个数据
const data={
name:'懿痕',
};
// send 不能发对象,要对data进行一个转换
let str=JSON.stringify(data)
// 设置响应体
response.send(str);
});
// 针对IE缓存
app.get('/ie',(request,response)=>{
// 设置响应头,设置允许跨域
response.setHeader('Access-Control-Allow-Origin',"*");
// 设置响应体
response.send('HELLO IE-2');
});
// 延时响应
app.get('/delay',(request,response)=>{
// 设置响应头,设置允许跨域
response.setHeader('Access-Control-Allow-Origin',"*");
// 设延时
setTimeout(()=>{
// 设置响应体
response.send('延时响应');
},3000)
});
// 4. 监听端口,启动服务
app.listen(8000,()=>{
console.log('服务已经启动,8000端口监听中.....')
})
Ajax Get 请求
<!DOCTYPE html>
<html lang="en">
<h
ead>
<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: 200px;
border: solid 1px ;
}
</style>
</head>
<body>
<button>点击发送请求</button>
<div id="result"></div>
<script>
let btn=document.querySelector('button');
let res=document.querySelector('#result');
// 绑定事件
btn.onclick=function(){
// 1. 创建对象
const xhr=new XMLHttpRequest();
// 2. 初始化,设置请求的方法和url
// 设置请求参数,在url后面用?分隔,名字=值,多个参数用&分隔
xhr.open('GET','http://127.0.0.1:8000/server?a=100&b=300');
// 3. 发送
xhr.send();
// 4. 事件绑定,处理服务端返回的结果
/* on ---when 当...的时候
readystate 是xhr对象中的一个属性,表示状态 0,1,2,3,4
0:表示未初始化
1:表示open方法调用完毕
2:表示send方法调用完毕
3:表示服务端返回部分结果
4:表示服务端返回所有结果
change 改变
即 当状态改变时触发
*/
xhr.onreadystatechange=function(){
// 判断(服务端返回所有结果)
if(xhr.readyState===4){
// 判断响应状态码 200 404 403 401 500
// 响应状态码中2开头的都表示成功
if(xhr.status>=200&&xhr.status<300){
// 处理结果 行 头 空行 体
// 1. 响应行
// console.log(xhr.status); // 状态码
// console.log(xhr.statusText); //响应状态字符串
// console.log(xhr.getAllResponseHeaders());// 所有的响应头
// console.log(xhr.response);//响应体
// 设置result的文本
res.innerHTML=xhr.response;
}
}
}
}
</script>
</body>
</html>
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: 1px solid #903;
}
</style>
</head>
<body>
<div id="result"></div>
<script>
// 获取元素对象
const result=document.querySelector('#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');
/*
Content-Type:用来设置请求体内容的类型
后面的是参数查询字符串的类型,固定的写法
*/
xhr.setRequestHeader('name','yihen');
// 3. 发送
// post请求参数设置
xhr.send('a=100&b=200'); // 第一种方式
// xhr.send('a:100&b:200'); //第二种方式
// xhr.send('123');
// 4. 事件绑定
xhr.onreadystatechange=function(){
// 状态判断
if(xhr.readyState===4){
if(xhr.status>=200&&xhr.status<300){
// 处理服务端返回的结果
result.innerHTML=xhr.response;
}
}
}
})
</script>
</body>
</html>
Ajax 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>Document</title>
<style>
#result{
width: 200px;
height: 100px;
border: solid 1px;
}
</style>
</head>
<body>
<div id="result"></div>
<script>
let result=document.querySelector('#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<300&&xhr.status>=200){
//
// console.log(xhr.response);
// result.innerHTML=xhr.response;
// 手动对数据进行转换
// let data=JSON.parse(xhr.response);
// console.log(data);
// result.innerHTML=data.name;
// 自动转换,设置 xhr.responseType='json'
result.innerHTML=xhr.response.name;
}
}
}
}
</script>
</body>
</html>
IE 缓存问题
<!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>Document</title>
<style>
#result{
width: 200px;
height: 100px;
border: 1px solid;
}
</style>
</head>
<body>
<button>点击发送请求</button>
<div id="result"></div>
<script>
const btn=document.querySelector('button');
const result=document.querySelector('#result');
btn.addEventListener('click',function(){
const xhr=new XMLHttpRequest();
// 针对IE缓存问题,加上时间戳,让每次的请求都不一样
xhr.open('GET','http://127.0.0.1:8000/ie?t='+Data.now());
xhr.send();
xhr.onreadystatechange=function(){
if(xhr.readyState===4){
if(xhr.status>=200&&xhr.status<300){
result.innerHTML=xhr.response;
}
}
}
})
</script>
</body>
</html>
请求超时或网络异常
<!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: 1px solid;
}
</style>
</head>
<body>
<button>点击发送请求</button>
<div id="result"></div>
<script>
const btn=document.querySelector('button');
const result=document.querySelector('#result');
btn.addEventListener('click',function(){
const xhr=new XMLHttpRequest();
// 超时设置
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>
取消请求
<!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 xhr=new XMLHttpRequest();
btns[0].addEventListener('click',function(){
xhr.open('GET','http://127.0.0.1:8000/delay');
xhr.send();
})
// abort 取消请求
btns[1].onclick=function(){
xhr.abort();
}
</script>
</body>
</html>
重复请求问题
<!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>
<script>
// 获取元素
const btns=document.querySelectorAll('button');
let xhr=new XMLHttpRequest();
// 标识变量
let isSending=false;// 是否正在发送Ajax请求
btns[0].addEventListener('click',function(){
// 判断标识变量
if(isSending) xhr.abort();// 如果正在发送就取消,发送一个新的
isSending=true;
xhr.open('GET','http://127.0.0.1:8000/delay');
xhr.send();
xhr.onreadystatechange=function(){
if(xhr.readyState===4){
// 修改标识变量
isSending=false;
}
}
})
</script>
</body>
</html>