原生JS封装ajax方法

 1 /* 封装ajax函数
 2  * @param {string}opt.type http连接的方式,包括POST和GET两种方式
 3  * @param {string}opt.url 发送请求的url
 4  * @param {boolean}opt.async 是否为异步请求,true为异步的,false为同步的
 5  * @param {object}opt.data 发送的参数,格式为对象类型
 6  * @param {function}opt.success ajax发送并接收成功调用的回调函数
 7  */
 8     function ajax(opt) {
 9         opt = opt || {};
10         opt.method = opt.method.toUpperCase() || 'POST';
11         opt.url = opt.url || '';
12         opt.async = opt.async || true;
13         opt.data = opt.data || null;
14         opt.success = opt.success || function () {};
15         var xmlHttp = null;
16         if (XMLHttpRequest) {
17             xmlHttp = new XMLHttpRequest();
18         }
19         else {
20             xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
21         }var params = [];
22         for (var key in opt.data){
23             params.push(key + '=' + opt.data[key]);
24         }
25         var postData = params.join('&');
26         if (opt.method.toUpperCase() === 'POST') {
27             xmlHttp.open(opt.method, opt.url, opt.async);
28             xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');
29             xmlHttp.send(postData);
30         }
31         else if (opt.method.toUpperCase() === 'GET') {
32             xmlHttp.open(opt.method, opt.url + '?' + postData, opt.async);
33             xmlHttp.send(null);
34         } 
35         xmlHttp.onreadystatechange = function () {
36             if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
37                 opt.success(xmlHttp.responseText);
38             }
39         };
40     }

使用如下:

ajax({
    method: 'POST',
    url: 'test.php',
    data: {
        name1: 'value1',
        name2: 'value2'
    },
    success: function (response) {
       console.log(response);
    }
});

  

原文地址:https://www.cnblogs.com/weixuechao/p/7738378.html