JS 原生JS封装AJAX,以及使用Promise封装AJAX示例以及使用

1.代码:

 1 function ajax(options) {
 2         options = options || {};
 3         options.type = options.type || 'get';
 4         data = options.data || {};
 5         // 处理数据
 6         var str = '';
 7         for (var i in data) {
 8             //str += `${i}=${data[i]}&`;  //IE不兼容模板字符串 ----update by 12-02
 9             str = str + i + '=' + data[i] + '&';
10         }
11         // 判断type类型拼接url
12         if (options.type == 'get' || options.type == 'jsonp') {
13             var d = new Date();
14             //url = `${options.url}?${str}d=${d.getTime()}`; //IE不兼容模板字符串  ----update by 12-02
15             url = options.url + '?' + str + '_jwy' + '=' + d.getTime();
16         } else {
17             url = options.url;
18         }
19         // console.log(`拼接后的url是${url}`);
20         // 判断type类型走jsonp还是创建ajax
21         if (options.type == 'jsonp') {
22             var script = document.createElement('script');
23             script.src = url;
24             document.body.appendChild(script);
25             // console.log(`走了jsonp的方法,url是${url}`)
26             window[data[data.colmName]] = function (responseText) {
27                 options.success(responseText);
28             };
29         } else {
30             var xhr;
31             //兼容性
32             if (window.XMLHttpRequest) {
33                 xhr = new XMLHttpRequest();
34             } else if (window.ActiveObject) {
35                 xhr = new ActiveXobject('Microsoft.XMLHTTP');
36             }
37             // 发送请求
38             if (options.type == 'get') {
39                 // console.log(`走了get的方法,url是${url}`)
40                 xhr.open('get', url, true);
41                 xhr.send(null);
42             } else {
43                 // console.log(`走了post的方法,url是${options.url},参数是${str}`)
44                 xhr.open('post', url, true);
45                 xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
46                 xhr.send(str.slice(0, str.length - 1));
47             }
48             // 接收数据
49             xhr.onreadystatechange = function () {
50                 if (xhr.readyState == 4) {
51                     var status = xhr.status;
52                     if (xhr.readyState == 4 && xhr.status == 200) {
53                         options.success(xhr.responseText, xhr.status);
54                     } else {
55                         options.error(xhr.responseText, xhr.status);
56                     }
57                 }
58             };
59         }
60     }

2.本地data.php中的数据:

<?php
    $u = $_REQUEST["user"];
    $p = $_REQUEST["pass"];
    echo "这是php数据".$u ."-----".$p;

3.使用示例:

  POST请求:

 1 ajax({
 2             url:"data.php",
 3             data:{
 4                 user:"admin",
 5                 pass:23213
 6             },
 7             type:"post",
 8             success:function(res,status){
 9                 console.log(res);
10                 console.log(status);
11             },
12             error:function(res,status){
13                 console.log(res);
14                 console.log(status);
15             }
16         })

  GET请求:

 1 //type不传默认是get
 2         ajax({
 3             url:"data.php",
 4             data:{
 5                 user:"admin",
 6                 pass:23213
 7             },
 8             success:function(res,status){
 9                 console.log(res);
10                 console.log(status);
11             },
12             error:function(res,status){
13                 console.log(res);
14                 console.log(status);
15             }
16         })

  JSONP:

 1 //以百度搜索接口为例
 2         ajax({
 3             url:"https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su",
 4             data:{
 5                 wd:"上海",
 6                 colmName:"cb",
 7                 cb:"adsaa"
 8             },
         type:'jsonp',
9 success:function(res,status){ 10 console.log(res); 11 console.log(status); 12 }, 13 error:function(res,status){ 14 console.log(res); 15 console.log(status); 16 } 17 })

 B:使用Promise封装

  代码:

 1  const ajax = options => {
 2         return new Promise((resolve, reject) => {
 3             options = options || {};
 4             options.type = options.type || 'get';
 5             data = options.data || {};
 6             // 处理数据
 7             var str = '';
 8             for (var i in data) {
 9                 str = str + i + '=' + data[i] + '&';
10             }
11             // 判断type类型拼接url
12             if (options.type == 'get' || options.type == 'jsonp') {
13                 var d = new Date();
14                 url = options.url + '?' + str + '_jwy' + '=' + d.getTime();
15             } else {
16                 url = options.url;
17             }
18             // 判断type类型走jsonp还是创建ajax
19             if (options.type == 'jsonp') {
20                 var script = document.createElement('script');
21                 script.src = url;
22                 document.body.appendChild(script);
23                 window[data[data.colmName]] = function (responseText) {
24                     resolve(responseText);
25                 };
26             } else {
27                 var xhr;
28                 //兼容性
29                 if (window.XMLHttpRequest) {
30                     xhr = new XMLHttpRequest();
31                 } else if (window.ActiveObject) {
32                     xhr = new ActiveXobject('Microsoft.XMLHTTP');
33                 }
34                 // 发送请求
35                 if (options.type == 'get') {
36                     // console.log(`走了get的方法,url是${url}`)
37                     xhr.open('get', url, true);
38                     xhr.send(null);
39                 } else {
40                     // console.log(`走了post的方法,url是${options.url},参数是${str}`)
41                     xhr.open('post', url, true);
42                     xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
43                     xhr.send(str.slice(0, str.length - 1));
44                 }
45                 // 接收数据
46                 xhr.onreadystatechange = function () {
47                     if (xhr.readyState == 4) {
48                         if (xhr.readyState == 4 && xhr.status == 200) {
49                             resolve(JSON.parse(xhr.responseText), xhr.status);
50                         } else {
51                             reject(xhr.responseText, xhr.status);
52                         }
53                     }
54                 };
55             }
56         });
57     };

使用示例:

  GET请求:

 1 ajax({
 2         url: 'https://tsapi.amap.com/v1/track/terminal/trsearch',
 3         data: {
 4             key: '2cc3573f7a73cb31cd75cfaa47e04957',
 5             sid: 151578,
 6             trid: 140,
 7             tid: 259087870,
 8             page: 1,
 9             pagesize: 20
10         }
11     }).then((res, status) => {
12         console.log(res, status);
13     }).catch((err, status) => {
14         console.log(err, status);
15     });

POST请求:

 1 ajax({
 2         url: 'data.php',
 3         data: {
 4             user: 'admin',
 5             pass: 23213
 6         },
 7         type: 'post',
 8     }).then((res,status)=>{
 9         console.log(res)
10         console.log(status)
11     }).catch((err,status)=>{
12         console.log(err)
13         console.log(status)
14     });

JSONP请求:

 1 ajax({
 2         url: 'https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su',
 3         data: {
 4             wd: '上海',
 5             colmName: 'cb',
 6             cb: 'adsaa'
 7         },
 8         type: 'jsonp'
 9     }).then((res, status) => {
10         console.log(res);
11         console.log(status);
12     }).catch((err, status) => {
13         console.log(err);
14         console.log(status);
15     });
posted @ 2019-11-30 16:10  半糖也甜吖  阅读(745)  评论(0编辑  收藏  举报