原生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     }
复制代码
使用示例:
复制代码
 1 ajax({
 2     method: 'POST',
 3     url: 'test.php',
 4     data: {
 5         name1: 'value1',
 6         name2: 'value2'
 7     },
 8     success: function (response) {
 9        console.log(response);
10     }
11 });
复制代码

猜你喜欢

转载自www.cnblogs.com/Mr5GG/p/9071488.html