IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> JavaScript知识库 -> Ajax与Axios学习笔记(一) -> 正文阅读

[JavaScript知识库]Ajax与Axios学习笔记(一)

作者:4.%E6%9B%B4%E6%96%B0%E6%95%B0%E6%8D%AE

目录

一、Ajax特点

二、HTTP协议

1.请求报文

1.1请求行

1.2请求头

1.3请求空行(necessary)

1.4请求体

2.响应报文

3.get请求

4.post请求

三、原生Ajax

1.express基本使用

2.ajax请求基本步骤

3.ajax方式get请求

4.ajax发送post请求

5.服务端响应json数据

6.IE浏览器缓存问题

7.网络异Ajax请求超时与常处理

8.取消请求?

四、axios

1.axios的配置

2.get的基本使用

3.post的基本使用

4.更新数据

5. 其他使用方法

6.axios默认配置

五、跨域

1.Ajax同源策略


一、Ajax特点

优点:

1.可以无需刷新页面与服务器进行通信

2.允许根据用户事件来更新部分页面内容

缺点:

1.没有浏览历史,不能回退

2.存在跨域问题(同源)

3.SEO(搜索引擎优化)不友好

二、HTTP协议

1.请求报文

1.1请求行

请求类型:GET、POST

url路径

HTTP协议版本

1.2请求头

host: mting.com
cookie: name = zmt
content - type: application / x - www - form - urlencoded

1.3请求空行(necessary)

1.4请求体

如果是get请求,请求体为空

如果是post请求, 请求体可为空可不为空

2.响应报文

响应行

HTTP协议版本

响应状态码(200, 404, 403, 500, 401等)

响应状态字符串

响应头

响应空行

响应体

3.get请求

const xhr = new XMLHttpRequest();
// 初始化,设置请求方法和url
xhr.open('GET', 'http://127.0.0.1:8000/server');
            

4.post请求

const xhr = new XMLHttpRequest();
// 初始化,设置请求方法和url
xhr.open('POST','http://127.0.0.1:8000/server');

三、原生Ajax

1.express基本使用

const express = require('express');
// 2.创建应用对象
const app = express();
// 3.创建路由规则
// request是对请求报文的封装
// response是对响应报文的封装
app.get('/',(request,response)=>{
    response.setHeader('Access-Control-Allow-Origin')
    // 设置响应
    response.send('HELLO EXPRESS')
});

app.all('/delay',(request,response)=>{
    response.setHeader('Access-Control-Allow-Origin','*')
    // 设置响应
    setTimeout(()=>{
        response.send('HELLO EXPRESS')
    },3000);
});
// 4.监听端口启动服务
app.listen(8000,()=>{
    console.log('服务已经启动,8000端口监听中...');
})

2.ajax请求基本步骤

?1.创建对象

?2.初始化 设置请求方法和url

?3.发送

?4.事件绑定 处理服务端返回的结果

3.ajax方式get请求

<script>
        const btn = document.getElementsByTagName('button')[0];
        const result = document.getElementById('result');
        btn.onclick = function () {
            // 1.创建对象
            const xhr = new XMLHttpRequest();
            // 初始化,设置请求方法和url
            xhr.open('GET', 'http://127.0.0.1:8000/server?');
            // 3.发送
            xhr.send();
            // 4.事件绑定 处理服务端返回的结果
            // on  when   当……时候
            // readyState 是xhr对象中的属性,表式状态0 1 2 3 4 
            // change  改变
            xhr.onreadystatechange = function () {
                // 判断响应状态码 200 404 403 401 500
                if (xhr.readyState === 4) {
                    // 判断响应状态码 200 404 403 401 500
                    // 2xx  成功

                    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.innerHTML = xhr.response;
                    } else {

                    }
                }
            }

        }
        
    </script>

4.ajax发送post请求

    <script>
        const btn = document.getElementsByTagName('button')[0];
        const result = document.getElementById('result');
        result.addEventListener('mouseover',function(){
            // 1.创建对象
            const xhr = new XMLHttpRequest();
            // 初始化,设置请求方法和url
            xhr.open('POST','http://127.0.0.1:8000/server');
            xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
            xhr.setRequestHeader('name','zmt')
             // 3.发送
            xhr.send('a=100&b:200')
            
            // xhr.send('a:100&b:300');
            // 4.事件绑定 处理服务端返回的结果
            // on  when   当……时候
            // readyState 是xhr对象中的属性,表式状态0 1 2 3 4 
            // change  改变
            xhr.onreadystatechange = function(){
                // 判断响应状态码 200 404 403 401 500
                if(xhr.readyState === 4){
                    // 判断响应状态码 200 404 403 401 500
                    // 2xx  成功
                    
                    if(xhr.status >= 200 && xhr.status <300){
                        
                        result.innerHTML = xhr.response;
                    }
                }
            }
            
        });
        
    </script>

5.服务端响应json数据

<script>
        const 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 >= 200 && xhr.status < 300){
                        console.log(xhr.response);
                        result.innerHTML = xhr.response.name;
                        
                    }
                }
            }
        }
</script>

6.IE浏览器缓存问题

解决方法: 在url路径最后加上时间戳,他就不会走缓存路线?

7.网络异Ajax请求超时与常处理

 <script>
        const btn = document.querySelector('button');
        const result = document.querySelector('.result');
        btn.addEventListener('click',function(){
            // console.log('test');
            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>

8.取消请求?

<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>

四、axios

1.axios的配置

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

2.get的基本使用

btn1.onclick = function(){
    axios({
      method:'GET',
      url:'http://localhost:3000/posts/2'
   }).then(response => {
       console.log(response);
     });
};

3.post的基本使用

btn2.onclick = function(){
            axios({
                method:'POST',
                url:'http://localhost:3000/posts',
                data:{
                    id:3,
                    title:'The weather is comfortable today!',
                    author:'mting'
                }
            }).then(response => {
                console.log(response);
            });
        };

4.更新数据

btn3.onclick = function(){
            axios({
                method:'PUT',
                url:'http://localhost:3000/posts/3',
                data:{
                    id:3,
                    title:'The weather is comfortable today!',
                    author:'professor'
                }
            }).then(response => {
                console.log(response);
            });
        };

5. 其他使用方法

btns[0].onclick = function(){
            axios.request({
                method:'GET',
                url:'http://localhost:3000/comments'
            }).then(response =>{
                console.log(response);
            })
        };
        btns[1].onclick = function(){
            axios.post(
                'http://localhost:3000/comments',
                {
                   'body':'喜大普奔',
                   'postId':2
            }).then(response =>{
                console.log(response);
            })
        }

6.axios默认配置

 <script>
        const btns = document.querySelectorAll('button');
        axios.defaults.method = 'GET';
        axios.defaults.baseURL = 'http://localhost:3000';
        btns[0].onclick = function(){
            axios({
                url:'/posts'
            }).then(response =>{
                console.log(response);
            })
        }
    </script>

7.请求取消

<body>
    <button>发送请求</button>
    <button>取消请求</button>
    <script>
        const btns = document.querySelectorAll('button');
        let cancel = null;
        btns[0].onclick = function(){
            if(cancel !==null){
                cancel();
            }
            axios({
                method:'GET',
                url:'http://localhost:3000/posts',
                cancelToken: new axios.CancelToken(function(c) {
                        // 将c的值赋值给cancel
                        cancel = c;
                        
                })
            }).then(response=>{
                console.log(response);
                cancel = null;
            })
        };
        btns[1].onclick = function(){
            cancel();
        }
    </script>
</body>

五、跨域

1.Ajax同源策略

同源策略是浏览器的一种安全策略,违背同源策略就是跨域

同源:协议,域名,端口号必需完全相同

其他问题:ajax中在控制台输入nodemon server.js报错

解决方法:在控制台输入npx nodemon server.js

axios使用文档:axios中文文档|axios中文网 | axios

json-server使用文档:GitHub - typicode/json-server: Get a full fake REST API with zero coding in less than 30 seconds (seriously)

  JavaScript知识库 最新文章
ES6的相关知识点
react 函数式组件 & react其他一些总结
Vue基础超详细
前端JS也可以连点成线(Vue中运用 AntVG6)
Vue事件处理的基本使用
Vue后台项目的记录 (一)
前后端分离vue跨域,devServer配置proxy代理
TypeScript
初识vuex
vue项目安装包指令收集
上一篇文章      下一篇文章      查看所有文章
加:2021-11-12 19:30:07  更:2021-11-12 19:32:13 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/10 10:23:15-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码