Ajax 入门

102 阅读3分钟

Ajax 学习笔记

Ajax的用途

AJAX 异步 js和xml的简称,主要用于非网页跳转的,异步服务请求

在学习的时候一般用node.js 建立一个后端服务器 ,一般可以 express 快速开发一个后端服务

终端 输入 npm i express 安装依赖

get /post 请求的区别

get 可以在是请求特点地址中的资源,提交的信息放在 url后面 比如 : http://127.0.0.1:8000/server?a=100&b=200&c=300 get 更多是用来取数据

  • GET 请求可被缓存
  • GET 请求保留在浏览器历史记录中
  • GET 请求可被收藏为书签
  • GET 请求不应在处理敏感数据时使用
  • GET 请求有长度限制
  • GET 请求只应当用于取回数据

post 更多是提交信息给特定的地址处理,因此提交信息放在 请求体里面 ,post 常用来提交表单

  • POST 请求不会被缓存
  • POST 请求不会保留在浏览器历史记录中
  • POST 不能被收藏为书签
  • POST 请求对数据长度没有要求

快速入门:

express 后端服务

// 引入
const express= require('express');
const { request } = require('http');

//创建 app
 const app= express();

 // 创建路由规则
  app.get('/server',(request,response)=>{
    // 设置报文头运行跨域
    response.setHeader('Access-Control-Allow-Origin','*');
    response.send('Hello AJAX');
  });

  app.listen(8000,()=>{
    console.log("服务已经启动,8000端口监听中...");
  })

前端建立一个 html 文档加入 js文档里面写入 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: 300px;
            border: 1px solid #ddd;
        }
    </style>
</head>
<body>
    <div id="text-in"> 
        <button>点击发送get请求
        </button>
        <div id="result">

        </div>
    </div>
    <script>
        let btn=document.querySelector('button');
        let result =document.querySelector('#result');
        btn.addEventListener('click',function(){
            // 创建对象
            const xhr=new XMLHttpRequest();
            xhr.open('GET','http://127.0.0.1:8000/server?a=100&b=200&c=300');// 问号后面的是传递到后端的参数
            xhr.send();
            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);//响应体
                         result.innerHTML=xhr.response;
                    }else{
                       console.log('连接失败');
                    }
                }
            }
        })
    </script>
</body>
</html>

使用 post 请求

先要在服务器端加入 post的响应体,请求信息放在send 里面 用 冒号形式或者是等号都可以用&隔开

  // 设置post 路由规则
  app.post('/server',(request,response)=>{
    response.setHeader('Access-Control-Allow-Origin','*');
    response.send('Hello 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 GET</title>
    <style>
        #result{
            width: 200px;
            height: 300px;
            border: 1px solid #ddd;
        }
    </style>
</head>
<body>
    <div id="text-in"> 
        <button>点击发送get请求
        </button>
        <div id="result">

        </div>
    </div>
    <script>
        let btn=document.querySelector('button');
        let result =document.querySelector('#result');
        btn.addEventListener('click',function(){
            // 创建对象
            const xhr=new XMLHttpRequest();
            xhr.open('POST','http://127.0.0.1:8000/server');
            xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
            xhr.send('a=100&b=200&c=300');
            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);//响应体
                         result.innerHTML=xhr.response;
                    }else{
                       console.log('连接失败');
                    }
                }
            }
        })
    </script>
</body>
</html>

Ajax 操作

先要创建对象 ,设置请求方式,url 和请求体

const result= new XMLHttpRequest();
// 初始化 设置 类型和URL
xhr.open('POST','http://127.0.0.1:8000/server');
// 设置请求头信息 第一个参数是键名,第二个是键值 一般使用预定义的
 xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
// 放入请求信息
xhr.send('a=100&b=200&c=300');
// 判断响应信息

使用 ajax传递 json对象

这里提供一种 nodemon插件 可以自动更新node后端开启终端

npm install -g nodemon 安装

(npx) nodemon server.js 启动方式

后端增加的内容

app.all('/json-server',(request,response)=>{
    response.setHeader('Access-Control-Allow-Origin','*');
    // response.setHeader('Access-Control-Allow-Headers','*');
    // 响应返回 data的json文件
    // response.send('Hello AJAX Json');
    const data={
        name:'kiri2'
    };
    let str=JSON.stringify(data);
    response.send(str);
  })

前端的内容

  let btn=document.querySelector('button');
        let result =document.querySelector('#result');
        btn.addEventListener('click',function(){
            // 创建对象
            const xhr=new XMLHttpRequest();
            xhr.open('POST','http://127.0.0.1:8000/json-server');
            xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
            xhr.send('a=100&b=200&c=300');
            xhr.responseType='json';// 自动转化json
            xhr.onreadystatechange=function(){
                if(xhr.readyState===4){
                    if(xhr.status>=200 && xhr.status<300){
                 
                        // 手动转化json 也可以在响应体里实现 
                        //  const data= JSON.parse(xhr.response);
                        const data =xhr.response;
                         result.innerHTML=data.name;
                         
                    }else{
                       console.log('连接失败');
                    }
                }
            }
        })

请求超时与网络异常

网络请求中容易出现断网或者是高延迟的情况因此需要进行处理

1.这人为制造服务端的延迟

服务器端可以设置 超时响应

           xhr.timeout=2000;
            xhr.ontimeout=function(){
                alert('网络异常');
            }
            //比如掉网
            xhr.onerror=function(){
                alert('网络出错了');
            }

服务端

app.get('/delay',(request,response)=>{
      response.setHeader('Access-Control-Allow-Origin','*');
      setTimeout(function(){
        response.send('延迟测试')
      },3000)
  })
<body>
    <button>发出请求</button>
    <button>中断请求</button>
    <script>
        const btns=document.querySelectorAll('button');
        const send= btns[0];
        const borts=btns[1];
         let x=null;
        send.onclick=function(){
            x= new XMLHttpRequest();
            x.open("GET",'http://127.0.0.1:8000/delay');
            x.send();
        }
        borts.onclick=function(){
            x.abort();
        }

    </script>
</body>

abort() 可以中断请求 因此可用于 防抖多次请求的情况

 const btns=document.querySelectorAll('button');
        const send= btns[0];
        const borts=btns[1];
         let x=null;
         let sended=false;
        send.onclick=function(){
           if (sended) x.abort();
            sended=true;
            x= new XMLHttpRequest();
            x.open("GET",'http://127.0.0.1:8000/delay');
            x.send();
        }

axios 工具库

封装 使用ajax 请求 ,这里使用了promise 异步操作 也可使用promise 里的 fetch 形成异步操作

引入工具库

<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.1.3/axios.js"> </script>

或者使用本地安装

npm install axios

这里使用 axios来发出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>axios</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/1.1.3/axios.js"> </script>
</head>
<body>
    
    <button>GET</button>
    <button>POST</button>
    <button>AJAX</button>
    <button>Fetch</button>
    <script>
        const btns=document.querySelectorAll('button');
        //配置默认的主机
        axios.defaults.baseURL='http://127.0.0.1:8000';
        // 发送 get 请求
        btns[0].onclick=function(){
          axios.get('/axios-server',{
            params:{
                id:100,
                vip:7
            },
            headers:{
                name:'jiangxi',
                age:20
            }
          }).then(value=>{
            console.log(value);
          });
        };
        //post 请求
        btns[1].onclick=function(){
            axios.post('/axios-server',{
                username:'admain',
                password:'admin'
            },{
                params:{
                    id:200,
                    vip:9
                },
                headers:{
                    height:180,
                    weight:180
                }
            }

            ).then(value=>{
            console.log(value);
          });
        }
        // 通过报文格式填写
        btns[2].onclick=function(){
         axios({
            url:'/axios-server',
            params:{
                vip:10,
                level:30
            },
            headers:{
                a:100,
                b:200
            },
            data:{
                username:'admin',
                password:'admin'
            }
         }).then(value=>{
            console.log(value);
          });
        }
        // 使用promis里面的fetch 函数形成异步操作
        btns[3].onclick=function(){
            fetch('http://127.0.0.1:8000/fetch-server?vip=100',{
                method:'POST',
                headers:{
                    name:'xxx'
                },
                body:'username=admin'
            }).then(value=>{
                console.log(value)
            })
        }
   </script>
</body>
</html>