赞
踩
利用Promise来请求数据是这样的
- <!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>
- <script>
- new Promise((resolve, reject) => {
- const url = "url地址";
- var xhr = new XMLHttpRequest();
- xhr.open("GET", url);
- xhr.send();
- xhr.onload = function () {
- var data = JSON.parse(xhr.response);
- resolve({ data });
- };
- xhr.onerror = function () {
- var data = JSON.parse(xhr.response);
- reject({ data });
- };
- })
- .then(res => {
- console.log("then:", res);
- })
- .catch(err => {
- console.log("catch:", err);
- });
- </script>
- </body>
- </html>
resolve触发时, 其参数会传递给 .then 方法
reject触发时, 其参数会传递给 .catch 方法
请求到的数据, 上方代码其实除了 url地址 不是固定的, 其余部分都是固定的, 那不如简单的封装一下, 看具体代码如下:
- const axios = {
- get(url) {
- return new Promise((resolve, reject) => {
- var xhr = new XMLHttpRequest();
- xhr.open("GET", url);
- xhr.send();
-
- xhr.onload = function () {
- resolve(JSON.parse(xhr.response));
- };
-
- xhr.onerror = function () {
- reject(JSON.parse(xhr.response));
- };
- })
- }
- }
就这几行代码就足够了, 我们来请求一下试一试
- <!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>
- </head>
- <body>
- <script src="./14.axios.js"></script>
- <script>
- const url = "url地址";
- axios.get(url).then(res => {
- console.log(res);
- });
- </script>
- </body>
- </html>
也是可以的, 是不是很简单
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。