1 //简易的ajax
2 $B.ajax = function(obj){
3 var xhr = $B.getXHR();//获取xhr对象
4 //默认true开启异步(异步和同步的主要区别是异步在请求的时候后面的脚本可以继续运行,同步的话必须运行完ajax然后才能运行其后面的脚本)
5 if(obj.async === true) {
6 xhr.onreadystatechange = function() {
7 if(xhr.readyState ==4) {
8 callback(xhr.responseText);
9 }
10 }
11 }
12
13 var arr=[] ;
14 for(var i in obj.data) {arr.push(encodeURIComponent(i)+'='+encodeURIComponent(obj.data[i]));}
15 obj.data = arr.join('&'); //这一步要注意一下,不管是get/post 方式提交都必须要对穿进来的obj.data进行格式化 最后转化成的格式name=zhang&age=26&wedding=no
16 if(obj.method === 'get') {//通过get方式请求的
17 obj.url = obj.url.indexOf('?') ==-1 ? obj.url+'?rand='+Math.random()+'&'+obj.data : obj.url+'rand='+Math.random()+'&'+obj.data;
18 xhr.open(obj.method,obj.url,obj.async);
19 xhr.send(null);
20 }
21
22 if(obj.method === 'post') {//通过post方式请求的
23 obj.url =obj.url+'?rand='+Math.random();
24 xhr.open(obj.method,obj.url,obj.async);
25 xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');//这是对请求头部的类型重设,post的请求必须要重设;
26 xhr.send(obj.data);
27 }
28
29 //false开启同步
30 if(obj.async === false) {
31 callback(xhr.responseText);
32 }
33 function callback (returnTxt) {
34 if(xhr.status == 200){
35 obj.success(returnTxt);
36 }
37 }
38 };
39
40 //判断是否为函数
41 $B.isFn = function(fn){
42 if(fn && typeof fn =='function') {
43 return true
44 }
45 return false;
46 };
47 $B.getXHR = function(){//获取xhr对象,为了兼容ie6所以进行了重新封装
48 if(typeof XMLHttpRequest !='undefined') {
49 return new XMLHttpRequest();
50 }else if(typeof ActiveXObject !='undefined') {
51 var version = [
52 'MSXML2.XMLHttp6.0',
53 'MSXML2.XMLHttp3.0',
54 'MSXML2.XMLHttp'
55 ]
56 for(var i in version) {
57 try{
58 return new ActiveXObject(version[i]);
59 break;
60 }catch(e){
61 //捕获错误进行然后跳出继续循环
62 }
63 }
64 }else{
65 throw new Error("您的系统或浏览器不支持XHR对象!");
66 }
67 };