封装ajax

 1 //封装ajax
 2 function ajax(obj) {
 3     var xhr = (function () {
 4         if (typeof XMLHttpRequest != 'undefined') {
 5             return new XMLHttpRequest();
 6         } else if (typeof ActiveXObject != 'undefined') {
 7             var version = [
 8                                         'MSXML2.XMLHttp.6.0',
 9                                         'MSXML2.XMLHttp.3.0',
10                                         'MSXML2.XMLHttp'
11             ];
12             for (var i = 0; version.length; i ++) {
13                 try {
14                     return new ActiveXObject(version[i]);
15                 } catch (e) {
16                     //跳过
17                 }    
18             }
19         } else {
20             throw new Error('您的系统或浏览器不支持XHR对象!');
21         }
22     })();
23     obj.url = obj.url + '?rand=' + Math.random();
24     obj.data = (function (data) {
25         var arr = [];
26         for (var i in data) {
27             arr.push(encodeURIComponent(i) + '=' + encodeURIComponent(data[i]));
28         }
29         return arr.join('&');
30     })(obj.data);
31     if (obj.method === 'get') obj.url += obj.url.indexOf('?') == -1 ? '?' + obj.data : '&' + obj.data;
32     if (obj.async === true) {
33         xhr.onreadystatechange = function () {
34             if (xhr.readyState == 4) {
35                 callback();
36             }
37         };
38     }
39     xhr.open(obj.method, obj.url, obj.async);
40     if (obj.method === 'post') {
41         xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
42         xhr.send(obj.data);    
43     } else {
44         xhr.send(null);
45     }
46     if (obj.async === false) {
47         callback();
48     }
49     function callback() {
50         if (xhr.status == 200) {
51             obj.success(xhr.responseText);            //回调传递参数
52         } else {
53             alert('获取数据错误!错误代号:' + xhr.status + ',错误信息:' + xhr.statusText);
54         }    
55     }
56 }

 

posted @ 2015-04-25 17:55  晚秋ing  阅读(122)  评论(0编辑  收藏  举报