ajax封装1

 1 (function (window) {
 2     function AjaxTool() {
 3     }
 4 
 5     AjaxTool.ajaxRequest = function (url, paramObj, successCallback, failedCallback) {
 6         var xhr = new XMLHttpRequest();
 7         xhr.open('get', url + '?' + getStrWithObject(paramObj), true);
 8         xhr.send();
 9         xhr.addEventListener('readystatechange', function (ev2) {
10            if(xhr.readyState === 4){
11                if(xhr.status === 200){
12                    // 请求成功
13                    successCallback && successCallback(xhr);
14                }else {
15                    // 请求失败
16                    failedCallback && failedCallback(xhr);
17                }
18            }
19         });
20     };
21 
22 
23     /*
24      {
25         name: "张三",
26         age: 18
27      }
28      [‘name="张三"’, “age=18”, "random=323323232"]
29      name="张三"&age=18
30    */
31     /**
32      *  把对象转换成拼接字符串
33      * @param {Object}paramObj
34      */
35     function getStrWithObject(paramObj) {
36         var resArr = [];
37         // 1. 转化对象
38         for (var key in paramObj) {
39             var str = key + '=' + paramObj[key];
40             resArr.push(str);
41         }
42         // 2. 拼接时间戳
43         resArr.push('random=' + getRandomStr());
44 
45         // 3. 数组转成字符串
46         return resArr.join('&');
47     }
48 
49     /**
50      * 获取随机时间戳
51      * @returns {number}
52      */
53     function getRandomStr() {
54         return Math.random() + (new Date().getTime());
55     }
56 
57     window.AjaxTool = AjaxTool;
58 })(window);

 

posted @ 2019-07-21 23:33  疏影横斜水清浅  阅读(128)  评论(0编辑  收藏  举报