AJAX

1.原生AJAX

  • AJAX简介
    • AJAX实际上就是异步的JS和XML,通过AJAX可以在浏览器中向服务器发送异步请求。最大的优势,无刷新获取数据。AJAX不是新的编程语言,而是一种将现有的标准组合在一起使用的新的方式
  • XML简介
    • XML可扩展标记语言,被设计用来传输和存储数据。XML和HTML类似,不同的是HTML中都是预定义标签,而XML中没有预定义标签,全都是自定义标签,用来表示一些数据
  • AJAX特点
    • 优点
      • 可以无需刷新页面与服务器进行通信
      • 允许你根据用户事件来更新部分分页内容
    • 缺点
      • 没有浏览历史,不能回退
      • 存在跨域问题(同源)
      • SEO不友好
  • HTTP:超文本传输协议,协议规定了浏览器和万维网服务器之间互相通信的规则
 1 #HTTP
 2 HTTP 【超文本传输协议】,协议详细规定了浏览器和万维网服务器之间通信的规则
 3 
 4 ##请求报文
 5 重点是格式与参数
 6 ...
 7 行        GET / URL / HTTP/1.1 
 8 头        Host:atguigu.com
 9         Cookie:name=guigu
10         Content-type:application/x-www.from-urlencoded
11         User-Agent:chrome 8
12 空行
13 体        GET(空)    / POST(可以为空)/username = admin
14 ...
15 
16 ##响应报文
17 ...
18 行        HTTP/1.1 200 OK
19 头        Content-type:text-html;charset = utf-8
20         Content-length:2048
21         Content-encoding:gzip
22 空行
23<html>
24             <head>
25                 <title></title>
26             </head>
27             <body>HTTP相应报文</body>
28         </html>
29 ...
  • express介绍
 1 //1.引入express
 2 const express = require('express');
 3 //2.创建应用对象
 4 const app = express();
 5 //3.创建路由规则
 6 //request是对请求报文的封装
 7 //response是对相应报文的封装
 8 app.get('/',(request,response)=>{
 9     //设置相应node
10     response.send("HELLO EXPRESS");
11 });
12 //监听端口启动服务
13 app.listen(8000,()=>{
14     console.log("服务已经启动, 8000端口监听中...")
15 })

2.GET和POST简单案例

  • GET
    • html页面
 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="utf-8">
 5         <title></title>
 6         
 7         <style type="text/css">
 8             #result {
 9                 height: 200px;
10                 width: 400px;
11                 border: 5px solid #CCC;
12             }
13         </style>
14     </head>
15     <body>
16         <button>点击发送请求</button>
17         <div id = "result"></div>
18         <script>
19             var btn = document.querySelector("button");
20             btn.onclick = function(){
21                 //1.创建对象
22                 const xhr = new XMLHttpRequest();
23                 //2.初始化 设置请求方法和URL
24                 xhr.open('GET','http://127.0.0.1:8000/server');
25                 //3.发送
26                 xhr.send();
27                 //4.事件绑定 处理服务器端返回的结果
28                 //readystate是对象中的属性,表示状态0(初始化),1(open),2(send),3(返回部分结果),4(返回所有结果)
29                 xhr.onreadystatechange = function(){
30                     //判断服务端返回了所有的结果
31                     if(xhr.readyState === 4){
32                         //判断相应的状态码
33                         //2xx都是成功
34                         if(xhr.status >= 200 && xhr.status < 300){
35                             //处理结果
36                             //1.响应行
37                             console.log(xhr.status);//状态码
38                             console.log(xhr.statusText);//状态字符串
39                             console.log(xhr.getAllResponseHeaders());//所有响应头
40                             console.log(xhr.response);//响应体
41                         }else{
42                             
43                         }
44                     }
45                 }
46             }
47         </script>
48     </body>
49 </html>
    • js
 1 //1.引入express
 2 const express = require('express');
 3 //2.创建应用对象
 4 const app = express();
 5 //3.创建路由规则
 6 //request是对请求报文的封装
 7 //response是对相应报文的封装
 8 app.get('/server',(request,response)=>{
 9     //设置响应头,设置允许跨域
10     response.setHeader("Access-Control-Allow-Origin","*");
11     //设置相应体
12     response.send("HELLO AJAX");
13 });
14 //监听端口启动服务
15 app.listen(8000,()=>{
16     console.log("服务已经启动, 8000端口监听中...")
17 })
  • POST
    • HTML
 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="utf-8">
 5         <title></title>
 6         
 7         <style type="text/css">
 8             #result {
 9                 height: 200px;
10                 width: 400px;
11                 border: 5px solid #CCC;
12             }
13         </style>
14     </head>
15     <body>
16         <button>点击发送请求</button>
17         <div id = "result"></div>
18         <script>
19             var btn = document.querySelector("button");
20             var result = document.querySelector("#result");
21             btn.onclick = function(){
22                 //1.创建对象
23                 const xhr = new XMLHttpRequest();
24                 //2.初始化 设置请求方法和URL
25                 xhr.open('POST','http://127.0.0.1:8000/server');
26                 //3.发送
27                 xhr.send();
28                 //4.事件绑定 处理服务器端返回的结果
29                 //readystate是对象中的属性,表示状态0(初始化),1(open),2(send),3(返回部分结果),4(返回所有结果)
30                 xhr.onreadystatechange = function(){
31                     //判断服务端返回了所有的结果
32                     if(xhr.readyState === 4){
33                         //判断相应的状态码
34                         //2xx都是成功
35                         if(xhr.status >= 200 && xhr.status < 300){
36                             //处理服务端返回结果
37                             result.innerHTML = xhr.response;
38                         }else{
39                             
40                         }
41                     }
42                 }
43             }
44         </script>
45     </body>
46 </html>
    • JS
 1 //1.引入express
 2 const express = require('express');
 3 //2.创建应用对象
 4 const app = express();
 5 //3.创建路由规则
 6 //request是对请求报文的封装
 7 //response是对相应报文的封装
 8 app.post('/server',(request,response)=>{
 9     //设置响应头,设置允许跨域
10     response.setHeader("Access-Control-Allow-Origin","*");
11     //设置相应体
12     response.send("HELLO AJAX");
13 });
14 //监听端口启动服务
15 app.listen(8000,()=>{
16     console.log("服务已经启动, 8000端口监听中...")
17 })
  • POST请求参数设置
 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="utf-8">
 5         <title></title>
 6         
 7         <style type="text/css">
 8             #result {
 9                 height: 200px;
10                 width: 400px;
11                 border: 5px solid #CCC;
12             }
13         </style>
14     </head>
15     <body>
16         <button>点击发送请求</button>
17         <div id = "result"></div>
18         <script>
19             var btn = document.querySelector("button");
20             var result = document.querySelector("#result");
21             btn.onclick = function(){
22                 //1.创建对象
23                 const xhr = new XMLHttpRequest();
24                 //2.初始化 设置请求方法和URL
25                 xhr.open('POST','http://127.0.0.1:8000/server');
26                 //设置请求头
27                 xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
28                 //3.发送
29                 xhr.send('a=100&b=200&c=300');
30                 //4.事件绑定 处理服务器端返回的结果
31                 //readystate是对象中的属性,表示状态0(初始化),1(open),2(send),3(返回部分结果),4(返回所有结果)
32                 xhr.onreadystatechange = function(){
33                     //判断服务端返回了所有的结果
34                     if(xhr.readyState === 4){
35                         //判断相应的状态码
36                         //2xx都是成功
37                         if(xhr.status >= 200 && xhr.status < 300){
38                             //处理服务端返回结果
39                             result.innerHTML = xhr.response;
40                         }else{
41                             
42                         }
43                     }
44                 }
45             }
46         </script>
47     </body>
48 </html>
  •  JSON
    • HTML
 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="utf-8">
 5         <title></title>
 6         <style type="text/css">
 7             .res {
 8                 width: 300px;
 9                 height: 150px;
10                 border: #CCCCCC 2px solid;
11             }
12         </style>
13     </head>
14     <body>
15         <div class="res"></div>
16         <script type="text/javascript">
17             const res = document.querySelector(".res");
18             window.onkeyup = function(){
19                 // console.log(1);
20                 //1.创建对象
21                 const xhr = new XMLHttpRequest();
22                 //2.初始化
23                 xhr.open('GET','http://127.0.0.1:8000/json-server');
24                 //3.发送
25                 xhr.send();
26                 //4.判断阶段
27                 xhr.onreadystatechange = function(){
28                     if(xhr.readyState === 4){
29                         if(xhr.status >= 200 && xhr.status < 300){
30                             //
31                             // console.log(xhr.response);
32                             // res.innerHTML = xhr.response;
33                             let data = JSON.parse(xhr.response);
34                             res.innerHTML = data.name;
35                         }
36                     }
37                 }
38             }
39         </script>
40     </body>
41 </html>
    • JS
 1 //1.引入express
 2 const express = require('express');
 3 //2.创建应用对象
 4 const app = express();
 5 //3.创建路由规则
 6 //request是对请求报文的封装
 7 //response是对相应报文的封装
 8 app.all('/json-server',(request,response)=>{
 9     //设置响应头,设置允许跨域
10     response.setHeader("Access-Control-Allow-Origin","*");
11     response.setHeader("Access-Control-Allow-Headers","*");
12     //设置相应体
13     
14     //相应一个数据
15     const data = {
16         name: 'Tom'
17     };
18     let str = JSON.stringify(data);
19     response.send(str);
20 });
21 //监听端口启动服务
22 app.listen(8000,()=>{
23     console.log("服务已经启动, 8000端口监听中...")
24 })
  • AJAX-nodemon自动重启工具安装
    • npm install -g nodemon安装
    • 启动服务时,使用nodemon代替,而非node
  • IE请求超时与网络异常:ontimeout、onerror
    • HTML
 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="utf-8">
 5         <title>超时与网络异常</title>
 6         <style type="text/css">
 7             .res {
 8                 width: 200px;
 9                 height: 100px;
10                 border: 2px solid #CCC;
11             }
12         </style>
13     </head>
14     <body>
15         <button>点击发送请求</button>
16         <div class="res"></div>
17         <script type="text/javascript">
18             var btn = document.querySelector("button");
19             btn.onclick = function(){
20                 const xhr = new XMLHttpRequest();
21                 xhr.open("GET","http://127.0.0.1:8000/chrome");
22                 //超时设置 2s
23                 xhr.timeout = 2000;
24                 xhr.ontimeout = function(){
25                     alert("网络超时,请稍后重试");
26                 }
27                 //网络异常
28                 xhr.onerror = function(){
29                     alert("您的网络似乎出了一些问题")
30                 }
31                 xhr.send();
32                 xhr.onreadystatechange = function(){
33                     if(xhr.readyState === 4){
34                         if(xhr.status >= 200 && xhr.status < 300){
35                             const res = document.querySelector(".res");
36                             res.innerHTML = xhr.response;
37                         }
38                     }
39                 }
40             }
41         </script>
42     </body>
43 </html>
    • JS
 1 const express = require('express');
 2 const app = express();
 3 app.all('/chrome',(request,response)=>{
 4     response.setHeader("Access-Control-Allow-Origin","*");
 5     setTimeout(()=>{
 6         response.send('延迟相应');
 7     },3000);
 8 })
 9 app.listen(8000,()=>{
10     console.log("服务已经启动, 8000端口监听中...")
11 })
  • 取消请求:abort()
 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="utf-8">
 5         <title></title>
 6     </head>
 7     <body>
 8         <button class="send">点击发送</button>
 9         <button class="cancel">点击取消</button>
10         <script type="text/javascript">
11             const send = document.querySelector(".send");
12             const cancel = document.querySelector(".cancel");
13             let xhr;
14             send.onclick = function(){
15                 xhr = new XMLHttpRequest();
16                 xhr.open("GET","http://127.0.0.1:8000/delay");
17                 xhr.send();
18             }
19             cancel.onclick = function(){
20                 xhr.abort();
21             }
22         </script>
23     </body>
24 </html>
  • AJAX请求重复发送
 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="utf-8">
 5         <title></title>
 6     </head>
 7     <body>
 8         <button class="send">点击发送</button>
 9         <script type="text/javascript">
10             const send = document.querySelector(".send");
11             const cancel = document.querySelector(".cancel");
12             let xhr;
13             let isSending = false;//是否正在发送AJAX请求
14             send.onclick = function(){
15                 if(!isSending){
16                     xhr = new XMLHttpRequest();
17                     isSending = true;
18                     xhr.open("GET","http://127.0.0.1:8000/delay");
19                     xhr.send();
20                     xhr.onreadystatechange = function(){
21                         //不加状态码判断,防止出现该请求是一个失败请求的情况
22                         if(xhr.readyState === 4){
23                             isSending = false;
24                         }
25                     }
26                 }
27             }
28         </script>
29     </body>
30 </html>

 3.JOuery中的AJAX

  • jOuery
 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="utf-8">
 5         <title></title>
 6         <script src="../js/jquery-3.6.0.js"></script>
 7     </head>
 8     <body>
 9         <h2>jQuery发送AJAX请求</h2>
10         <button class="btn-primary">GET</button>
11         <button class="btn-danger">POST</button>
12         <button class="btn-info">通用型方法ajax</button>
13         <script type="text/javascript">
14             $("button").eq(0).on("click",function(){
15                 $.get('http://127.0.0.1:8000/jquery-server',{a:100},function(data){
16                     console.log(data);
17                 },'json')
18             })
19             $("button").eq(1).on("click",function(){
20                 $.post('http://127.0.0.1:8000/jquery-server',{a:100},function(data){
21                     console.log(data);
22                 })
23             })
24             $("button").eq(2).on("click",function(){
25                 $.ajax({
26                     //url
27                     url:'http://127.0.0.1:8000/jquery-server',
28                     //参数
29                     data: {a:100,b:200},
30                     //请求参数
31                     type: 'GET',
32                     //响应体结果
33                     dataType: 'json',
34                     //成功的回调
35                     success:function(data){
36                         console.log(data)
37                     },
38                     //超时的回调
39                     timeout:2000,
40                     //失败的回调
41                     error:function(){
42                         console.log("出错啦!")
43                     },
44                     //头信息
45                     headers:{
46                         c:300,
47                         d:400,
48                     
49                     }
50                 })
51             })
52         </script>
53     </body>
54 </html>
  • jQuery发送jsonp请求
    • HTML
 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="utf-8">
 5         <title></title>
 6         <script src="../../js/jquery-3.6.0.js"></script>
 7         <style type="text/css">
 8             .res {
 9                 width: 400px;
10                 height: 200px;
11                 border: 5px solid skyblue;
12             }
13         </style>
14     </head>
15     <body>
16         <button type="button">点击发送jsonp请求</button>
17         <div class="res"></div>
18         <script type="text/javascript">
19             //点击按钮向9000端口发送请求
20             $("button").eq(0).on("click",function(){
21                 //url路径后面添加?callback=?(固定写法)
22                 $.getJSON('http://127.0.0.1:9000/jquery-jsonp-server?callback=?',function(data){
23                     $(".res").html(`
24                         名称: ${data.name}<br/>
25                         城市: ${data.city}
26                     `);
27                 })
28             })
29         </script>
30     </body>
31 </html>
    • JS
 1 const express = require('express');
 2 const app = express();
 3 app.all('/jquery-jsonp-server',(request,response)=>{
 4     const data = {
 5         name: 'BH',
 6         city: 'sour'
 7     }
 8     let str = JSON.stringify(data);
 9     //接受callback参数
10     let cb = request.query.callback;
11     response.send(`${cb}(${str})`);
12 })
13 
14 app.listen(9000,()=>{
15     console.log("正在监听");
16 })

4.axios发送AJAX请求

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="utf-8">
 5         <title>xios</title>
 6         <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
 7     </head>
 8     <body>
 9         <button class="btn-primary">GET</button>
10         <button class="btn-danger">POST</button>
11         <button class="btn-info">ajax</button>
12         <script type="text/javascript">
13             var btns = document.querySelectorAll("button");
14             axios.defaults.baseURL = "http://127.0.0.1:8000";
15             btns[0].onclick = function(){
16                 //GET请求
17                 //配置baseURL
18                 axios.get('/axios-server',{
19                     //url参数
20                     params: {
21                         id: 100,
22                         vip: 7
23                     },
24                     //请求头信息
25                     headers:{
26                         name:'BH'
27                     }
28                 }).then(value=>{//基于Promise
29                     console.log(value);
30                 })
31             }
32             btns[1].onclick = function(){
33                 //GET请求
34                 //配置baseURL
35                 axios.defaults.baseURL = "http://127.0.0.1:8000";
36                 axios.post('/axios-server',
37                     {
38                         username: 'admin',
39                         password: 'admin'
40                     },{
41                         params:{
42                             id: 200,
43                             vip: 9
44                         },
45                         //请求头信息
46                         headers:{
47                             name:'BH'
48                         }
49                     }
50                 ).then(value=>{//基于Promise
51                     console.log(value);
52                 })
53             }
54             btns[2].onclick = function(){
55                 axios({
56                     //请求方法
57                     method: 'POST',
58                     //url
59                     url:'/axios-server',
60                     params: {
61                         vip: 10,
62                         level: 30
63                     },
64                     //头信息:
65                     headers: {
66                         a: 100,
67                         b: 200
68                     },
69                     //请求体
70                     data: {
71                         username: 'admin',
72                         password: 'admin'
73                     }
74                 })
75             }
76         </script>
77     </body>
78 </html>

5.fetch函数发送ajax请求

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="utf-8">
 5         <title></title>
 6     </head>
 7     <body>
 8         <button type="button">AJAX请求</button>
 9         <script type="text/javascript">
10             const btn = document.querySelector("button");
11             btn.onclick = function(){
12                 fetch('http://127.0.0.1:8000/fetch-server',{
13                     method: 'POST',
14                     //请求头
15                     headers: {
16                         name: 'BH'
17                     },
18                     //请求体
19                     body: 'username=admin&password=admin'
20                 }).then(response=>{
21                     return response.json();
22                 }).then(response=>console.log(response));
23             }
24         </script>
25     </body>
26 </html>

6.跨域

  • 同源策略
    • 同源:协议、域名、端口号,必须完全相同
  • index.html
 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="utf-8">
 5         <title>首页</title>
 6     </head>
 7     <body>
 8         <h1>BH</h1>
 9         <button>点击获取用户数据</button>
10         <script type="text/javascript">
11             const btn = document.querySelector("button");
12             btn.onclick = function(){
13                 const xhr = new XMLHttpRequest();
14                 //这里因为满足同源策略,url可以简写
15                 // xhr.open('GET','http://127.0.0.1:9000/data');
16                 xhr.open('GET','/data');
17                 xhr.send();
18                 xhr.onreadystatechange = function(){
19                     if(xhr.readyState === 4){
20                         if(xhr.status >= 200 && xhr.status < 300){
21                             console.log(xhr.response);
22                         }
23                     }
24                 }
25             }
26         </script>
27     </body>
28 </html>
    • server.js
 1 const express = require('express');
 2 const app = express();
 3 app.get('/home',(request,response)=>{
 4     //响应一个页面
 5     response.sendFile(__dirname+'/index.html')
 6 });
 7 
 8 app.get('/data',(request,response)=>{
 9     //响应一个页面
10     response.send('用户数据');
11 });
12 
13 app.listen(9000,()=>{
14     console.log('服务已经启动');
15 })
  • 解决跨域
    • jsonp
      • jsonp(JSON with padding)是一个非官方的跨域解决方案
      • JSONP利用script标签的跨域能力来发送请求
    • 原理.html
 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="utf-8">
 5         <title></title>
 6     </head>
 7     <body>
 8         <div></div>
 9         <script type="text/javascript">
10             var div = document.querySelector("div"); 
11             function handle(data){
12                 console.log(data);
13                 div.innerHTML = data.name;
14             }
15         </script>
16         <script src="http://127.0.0.1:9000/home"></script>
17     </body>
18 </html>
    • app.js
 1 const express = require('express');
 2 const app = express();
 3 app.all('/home',(request,response)=>{
 4     const data = {
 5         name: 'BH'
 6     }
 7     let str = JSON.stringify(data);
 8     response.send(`handle(${str})`);
 9 })
10 
11 app.listen(9000,()=>{
12     console.log("正在监听");
13 })
    • 原生jsonp实践
      • HTML
 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="utf-8">
 5         <title></title>
 6     </head>
 7     <body>
 8         用户名:<input class="username" type="text" />
 9         <p></p>
10         <script type="text/javascript">
11             //获取input元素
12             var input = document.querySelector(".username");
13             var p = document.querySelector('P');
14             //绑定事件
15             input.onblur = function(){
16                 let name = input.value;
17                 //向服务端发送请求,检测用户名是否存在
18                 //1.创建script标签
19                 const script = document.createElement('script');
20                 //2.设置标签属性
21                 script.src = `http://127.0.0.1:9000/test?name=${name}`;
22                 //3.将script插入文档中
23                 document.querySelector("body").appendChild(script);
24             }
25             
26             function handle(data){
27                 p.innerHTML = data.msg;
28             }
29         </script>
30     </body>
31 </html>
      • JS
 1 const express = require('express');
 2 const app = express();
 3 app.all('/test',(request,response)=>{
 4     const data = {
 5         exist: 1,
 6         msg: '用户名已存在'
 7     }
 8     let str = JSON.stringify(data);
 9     response.send(`handle(${str})`);
10 })
11 
12 app.listen(9000,()=>{
13     console.log("正在监听");
14 })
  • 设置CORS响应头实现跨域:https://developer.mozilla.org/zh-CN/docs/Web/HTTP
    • CORS,跨域资源共享,是官方的跨域解决方案。它的特点是不需要在客户端做任何特殊的操作,完全在服务器端进行处理,支持get和post请求。跨域资源共享标准新增了一组HTTP首部字段,允许服务器声明哪些源站通过浏览器权限访问哪些资源
posted @ 2022-04-25 19:59  Miraitowa56  阅读(49)  评论(0)    收藏  举报