Ashun's 技術駅 Ashun's 技術駅
首页
  • 前端文章

    • JavaScript
  • 学习笔记

    • 《JavaScript教程》
    • 《JavaScript高级程序设计》
    • 《ES6 教程》
    • 《Vue》
    • 《React》
    • 《TypeScript 从零实现 axios》
    • 《Git》
    • TypeScript
    • JS设计模式总结
  • HTML
  • CSS
  • Vue
  • 现代web布局
  • React
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • 技术资源
  • 第一阶段

    • HTML
  • 第二阶段

    • JavaScript
  • 第三阶段

    • Vue
  • 第四阶段

    • 实战项目
  • 每周测试

    • 每周
  • 其他

    • Vue引入UI框架
    • Web前端面试
    • Vue3-resource
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 福利资源
  • 友情链接
关于
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)

Ashun

前端界的小学生
首页
  • 前端文章

    • JavaScript
  • 学习笔记

    • 《JavaScript教程》
    • 《JavaScript高级程序设计》
    • 《ES6 教程》
    • 《Vue》
    • 《React》
    • 《TypeScript 从零实现 axios》
    • 《Git》
    • TypeScript
    • JS设计模式总结
  • HTML
  • CSS
  • Vue
  • 现代web布局
  • React
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • 技术资源
  • 第一阶段

    • HTML
  • 第二阶段

    • JavaScript
  • 第三阶段

    • Vue
  • 第四阶段

    • 实战项目
  • 每周测试

    • 每周
  • 其他

    • Vue引入UI框架
    • Web前端面试
    • Vue3-resource
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 福利资源
  • 友情链接
关于
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
  • 01变量
  • 02常量
  • 03js数据类型
  • 04运算、判断、条件
  • 05数字类型
  • 06字符串
  • 07布尔值
  • 08空值
  • 09未定义
  • 10唯一值
  • 11对象
  • 13数组
  • 14函数
  • 15日期对象
  • 16正则表达式
  • 17异常错误对象
  • 18BOM 浏览器对象模型
  • 19DOM文档对象模型
  • 20json
  • 21Ajax
    • 一、get请求
    • 二、post请求
      • 1) 请求报文和响应报文
      • 2) http请求
    • 三、get和post的区别
      • 1) 状态码
      • 2) 请求文本类型
      • 3) token
    • 四、axios
      • 易用、简洁且高效的http库
      • axios中文文档
      • 执行多个并发请求
      • 拦截器
      • 取消请求
  • 22jQuery
  • 23函数进阶
  • 24面向对象
  • 《javascript(es5)》
ashun
2022-02-14
目录

21Ajax

# Ajax

async javascript xml,异步js和xml。Ajax 允许通过与场景后面的 Web 服务器交换数据来异步更新网页。这意味着可以更新网页的部分,而不需要重新加载整个页面。

# 一、get请求

let xhr = new XMLHttpRequest();//实例化xhr对象

xhr.open("GET", "<http://vt.ossjk.com/goods/getIndexInfo>");//建立连接

xhr.send()//发送请求

xhr.onreadystatechange = function () {//响应请求
  if (xhr.readyState === 4 && xhr.status === 200) {
    console.log(JSON.parse(xhr.response));
  }
};
1
2
3
4
5
6
7
8
9
10
11

练习中💨

获取列表接口 get请求 不用写参数 http://192.168.1.176:8080/getList

var xhr
if(window.XMLHttpRequest){//判断浏览器是否支持XMLHttpRequest
    xhr = new XMLHttpRequest()//实例化xhr对象
}else{//做ie5\ie6的兼容
    xhr = new ActiveXObject("Microsoft.XMLHTTP")
}

xhr.open("GET","http://192.168.1.176:8080/getList")//与服务器地址建立连接

xhr.send()//发送请求

xhr.onreadystatechange = function(){//等待服务器响应
    if(xhr.readyState === 4 && xhr.status === 200){//判断服务器是否接收成功
        console.log(JSON.parse(xhr.response))//服务器的响应
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# 二、post请求

let xhr = new XMLHttpRequest();//实例化xhr对象
      
xhr.open("POST", "<http://vt.ossjk.com/goods/getDetailGoodsInfo>");//建立连接

xhr.setRequestHeader("content-type", "application/json");//设置请求头

let data = {
  goodsId:"b1195296679f482aa7d54d95ac2b4a94"
}

xhr.send(JSON.stringify(data))//发送请求

xhr.onreadystatechange = function () {//响应请求
  if (xhr.readyState === 4 && xhr.status === 200) {
    console.log(JSON.parse(xhr.response));
  }
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

练习中💨

获取国家接口 post请求 传国家id http://192.168.1.176:8080/getCountry

var xhr
if(window.XMLHttpRequest){//判断浏览器是否支持XMLHttpRequest
xhr = new XMLHttpRequest()//实例化xhr对象
}else{//做ie5\ie6的兼容
xhr = new ActiveXObject("Microsoft.XMLHTTP")
}

xhr.open("POST","http://192.168.1.176:8080/getCountry")//与服务器地址建立连接

xhr.setRequestHeader("content-type", "application/json");//设置请求头

// 发给后端的参数
var data = {
"id":"001"
}

xhr.send(JSON.stringify(data))//发送请求

xhr.onreadystatechange = function(){//等待服务器响应
if(xhr.readyState === 4 && xhr.status === 200){//判断服务器是否接收成功
console.log(JSON.parse(xhr.response))//服务器的响应
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

获取城市接口 post请求 传城市id http://192.168.1.176:8080/getCity

var xhr
if (window.XMLHttpRequest) {//判断浏览器是否支持XMLHttpRequest
xhr = new XMLHttpRequest()//实例化xhr对象
} else {//做ie5\ie6的兼容
xhr = new ActiveXObject("Microsoft.XMLHTTP")
}

xhr.open("POST", "http://192.168.1.219:8080/getCity")//与服务器地址建立连接

xhr.setRequestHeader("content-type", "application/json");//设置请求头

var data = {
"id": "001002"
}

xhr.send(JSON.stringify(data))//发送请求

xhr.onreadystatechange = function () {//等待服务器响应
if (xhr.readyState === 4 && xhr.status === 200) {//判断服务器是否接收成功
console.log(JSON.parse(xhr.response))//服务器的响应
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

%accordion% 这是我们发送请求了 %accordion%

image-20211227174646878

%/accordion%

%accordion% 请求三大块 %accordion% image-20211227174923998

%/accordion%

# 1) 请求报文和响应报文

//发送的请求是有固定格式的
请求报文
	请求行 请求地址、请求类型(请求方法)、状态代码
	请求头 请求文本类型(json/form)、token(密钥)
	请求体 发送的参数
	
响应报文
	响应行
	响应头
	响应体 后端返回给前端的数据
1
2
3
4
5
6
7
8
9
10

请求报文

%accordion% 请求行%accordion%

image-20211227175416370

%/accordion%

%accordion% 这是后端了 %accordion%

image-20211227181059309

%/accordion%

%accordion% 请求头 %accordion%

image-20211227181844170

%/accordion%

%accordion% 请求体【post】 %accordion%

image-20211227182751136

%/accordion%

响应报文

%accordion% 响应返回字符串 %accordion%

image-20211227190748123

%/accordion%

%accordion% 预览返回对象✨ %accordion%

image-20211227191309873

%/accordion%

# 2) http请求

tcp/ip协议 
	<http://192.168.1.180:8080/getCountry>
	协议 http:// https:// ftp://
	域名 192.168.1.180 ip地址 域名、服务器
	端口号 :8080
	基本地址 <http://192.168.1.180:8080>
	功能地址 /getCountry
1
2
3
4
5
6
7

# 三、get和post的区别

1、get请求的参数会在地址栏上显示,而post不会
2、get请求的数据长度有限制(取决于url的长度),而post理论上没有限制
3、get比post更加不安全,数据会直接显示在url上
4、get会发送数据的时候会把请求头、请求数据等一次性发送,而post会先发送请求头然后再发送请求数据
1
2
3
4

(opens new window)

	按照restful风格 get一般不发送参数,post发送
请求类型
	get
		一般用于获取数据,不传参数
		在地址栏上面显示
		不安全
		参数有限制长度✨
	post
		一般用于获取指定,传参数
		在请求体显示
		不安全
		在发送的时候,会发两次,第一次是发送options,第二次才是真正的post
		理论上参数没有限制长度✨
1
2
3
4
5
6
7
8
9
10
11
12
13

# 1) 状态码

状态代码
	1xx 正在发送
	2xx 发送成功
	3xx 重定向
	4xx 前端错误
		404 地址错误
		400 参数错误
	5xx 后端错误
1
2
3
4
5
6
7
8

# 2) 请求文本类型

请求文本类型 content-type
	application/json    json类型✨
	application/x-www-form-urlencoded  表单类型✨
	multipart/form-data  上传类型
1
2
3
4

%accordion% json数据类型 %accordion%

image-20211227203810235

%/accordion%

# 3) token

token密钥
	http的请求缺陷,无法判断状态
	用途:判断用户是否在登陆
	后端生成,发送给前端,前端在每一个请求的请求头都带上这个token,就可以让后端判断该用户是否在登陆状态
	token是登陆的时候获取的,其他页面的请求一直带着
1
2
3
4
5
let xhr = new XMLHttpRequest();//实例化xhr对象

        xhr.open("POST", "http://vt.ossjk.com/goods/getDetailGoodsInfo");//建立连接

        xhr.setRequestHeader("content-type", "application/json");//设置请求头
        xhr.setRequestHeader("jwtToken", "f720d5f720d5e261ee0b63a292e261f720d5e261ee0b0bc71fe437c963a292ee0b0bc71fe437c963a292");//设置token秘钥

        let data = {
            goodsId: "001"
        }

        xhr.send(JSON.stringify(data))//发送请求

        xhr.onreadystatechange = function () {//响应请求
            if (xhr.readyState === 4 && xhr.status === 200) {
                console.log(JSON.parse(xhr.response));
            }
        };
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

image-20211227230916114

# 四、axios (opens new window)

[info] 什么是 axios? Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。

//get请求
axios
  .get("<http://vt.ossjk.com/goods/getIndexInfo>")
  .then((res)=>{
    console.log(res)
  })
//post请求
let data = {
  goodsId:"b1195296679f482aa7d54d95ac2b4a94"
}
axios
  .post("<http://vt.ossjk.com/goods/getIndexInfo>",data)
  .then((res)=>{
    console.log(res)
  })
//request请求
axios
  .request({
    url:"<http://vt.ossjk.com/goods/getIndexInfo>"
  })
  .then((res)=>{
    console.log(res)
  })
//request请求
let data = {
  goodsId: "b1195296679f482aa7d54d95ac2b4a94",
};
axios
  .request({
    url: "<http://vt.ossjk.com/goods/getIndexInfo>",
    method: "POST",
    data,
  })
  .then((res) => {
    console.log(res);
  });
//并发请求
function getIndexInfo(){
  return axios.get("<http://vt.ossjk.com/goods/getIndexInfo>")
}

function getCategoryList(){
  return axios.get("<http://vt.ossjk.com/goods/getCategoryList>")
}

axios
  .all([getIndexInfo(),getCategoryList()])
  .then(axios.spread((res1,res2)=>{
    console.log(res1)
    console.log(res2)
  }))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51

# 易用、简洁且高效的http库 (opens new window)

# axios中文文档 (opens new window)

%accordion% 安装 %accordion%

安装

使用 npm:

$ npm install axios
1

使用 bower:

$ bower install axios
1

使用 cdn:

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

%/accordion%

[!cogs]

GET请求 get是没有参数了

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
    axios
        .get("http://192.168.1.180:8080/getList")
        .then(function (response) {
            console.log(response);
        })
        .catch(function (error) {
            console.log(error);
        });
</script>

//仅参考
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
    axios
    .get("http://192.168.1.180:8080/getList",{
    params:{
        id:"9527"
    }
})
    .then(function (response) {
    console.log(response);
})
    .catch(function (error) {
    console.log(error);
});
</script>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

[!cogs]

post请求 post参数了

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
axios
.post("http://192.168.1.180:8080/getCountry", {

 	   id: "001"

    })
.then(function (response) {
console.log(response);
})
.catch(function (error) {
    	console.log(error);
    });
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# 执行多个并发请求

%accordion% 执行多个并发请求 %accordion%

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
function API_getList() {
    return axios.get("http://192.168.1.180:8080/getList")
}

function API_getCountry(id) {
return axios.post("http://192.168.1.180:8080/getCountry", {
   	 id: id
    })
}
axios.all([API_getList(), API_getCountry("001")])
        .then(axios.spread(function (res1, res2) {
            console.log(res1);
            console.log(res2);
}))

</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 //执行多个并发请求
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<script>
    axios.request({
        url: "http://192.168.1.180:8080/getList"
    }).then(function (res) {
        console.log(res);
    })
</script>

<script>
    axios.request({
        url: "http://192.168.1.180:8080/getCountry",
            method: "POST",
                data: {
                    id: "001"
                }
    }).then(function (res) {
        console.log(res);
    })
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

%/accordion%

# 拦截器

%accordion% 拦截器 %accordion%

添加请求拦截器

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

<script>
    // 添加请求拦截器
    axios.interceptors.request.use(
        function (config) {
            // 在发送请求之前做些什么
            config.headers.jwtToken = "9527";
            return config;
        },
        function (error) {
            // 对请求错误做些什么
            return Promise.reject(error);
        }
    );

    // 添加响应拦截器
    axios.interceptors.response.use(
        function (response) {
            // 对响应数据做点什么
            if (response.data.code === 200) {
                alert("操作成功");
            } else {
                alert("操作失败");
            }
            return response;
        },
        function (error) {
            // 对响应错误做点什么
            return Promise.reject(error);
        }
    );


    axios.request({
        url: "http://192.168.1.180:8080/getList"
    }).then(function (res) {
        console.log(res);
    })


    axios.request({
        url: "http://192.168.1.180:8080/getCountry",
        method: "POST",
        data: {
            id: "001"
        }
    }).then(function (res) {
        console.log(res);
    })
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51

%/accordion%

# 取消请求

%accordion% 取消请求【1】 %accordion%

<button class="stop">111</button>

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
    var stopBtn = document.querySelector(".stop");
    var source = axios.CancelToken.source();
    var http = axios.create({
        baseURL: "http://192.168.1.180:8080",
    });

    http
        .request({
        url: "getList",
        cancelToken: source.token,
    })
        .then(function (res) {
        console.log(res);
    });
    stopBtn.onclick = function () {
        source.cancel("取消请求1");
    };
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

%/accordion%

%accordion% 取消请求【2】 %accordion%

<button class="stop">111</button>

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
    var stopBtn = document.querySelector(".stop");

    var CancelToken = axios.CancelToken;

    var cancel;

    var http = axios.create({
        baseURL: "http://192.168.1.180:8080",
    });

    http
        .request({
        url: "getList",
        cancelToken: new CancelToken(function executor(c) {
            // executor 函数接收一个 cancel 函数作为参数
            cancel = c;
        }),
    })
        .then(function (res) {
        console.log(res);
    });
    stopBtn.onclick = function () {
        cancel("取消请求2");
    };
</script> 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

%/accordion%

%accordion% 取消请求【3】 %accordion%

<button class="stop">111</button>

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
    var stopBtn = document.querySelector(".stop");

    var CancelToken = axios.CancelToken;


    var http = axios.create({
        baseURL: "http://192.168.1.180:8080",
    });

    http
        .request({
        url: "getList",
        cancelToken: new CancelToken(function executor(c) {
            // executor 函数接收一个 cancel 函数作为参数
            cancelFn(c)
        }),
    })
        .then(function (res) {
        console.log(res);
    });

    function cancelFn(c) {
        c("取消请求3")
    }

    stopBtn.onclick = cancelFn
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

%/accordion%

编辑 (opens new window)
上次更新: 2022/04/24, 13:33:34
20json
22jQuery

← 20json 22jQuery→

最近更新
01
课件-react路由-V6
01-22
02
课件-国际化
01-22
03
课件-redux-toolkit
01-22
更多文章>
Theme by Vdoing | Copyright © 2019-2024 Evan Xu | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式