ajax封装

 1 var createXHR=function(){

 2       if(typeof XMLHttpRequest!="undefined"){

 3           return new XMLHttpRequest();

 4       }else if(typeof ActiveXObject!="undefined"){

 5           var version=["MSXML2.XMLHttp.6.0",

 6                        "MSXML2.XMLHttp.3.0",

 7                        "MSXML2.XMLHttp"];

 8           for(var i=0,len=version.length;i<len;i++){

 9               try{

10                   return new ActiveXObject(version[i]);

11               }catch(ex){

12                   //跳过

13               }

14           }

15       }else{

16           throw new Error("您的浏览器不支持ajax");

17       }

18 };

19 

20 //名值对转化为字符串

21 function params(data){

22     var arr=[];

23     for(var i in data){

24         arr.push(encodeURIComponent(i)+"="+encodeURIComponent(data[i]));

25     }

26     return arr.join("&");

27 }

28 

29 //封装ajax

30 function ajax (obj){

31     var xhr=createXHR();

32     obj.url = obj.url+"?rand="+Math.random()+"&"+params(obj.data);    

33     if(obj.method === "get"){  //get请求

34         obj.url = obj.url+(obj.url.indexOf("?")==-1 ? "?" : "&")+params(obj.data);

35     }

36     

37     if(obj.async==true){  //异步请求

38        xhr.onreadystatechange=function(){

39            if(xhr.readyState == 4){

40                 callback();

41            }

42        };

43     }

44     xhr.open(obj.method,obj.url,obj.async);

45     

46     if(obj.method === "post"){   //post请求

47         xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

48         xhr.send(params(obj.data));

49     }else{

50        xhr.send(null);

51     }

52     

53     if(obj.async == false){

54         callback();

55     }

56     function callback(){

57         if(xhr.status == 200){

58             obj.success(xhr.responseText);  //回调函数传递参数

59         }else{

60             alert("获取数据错误!错误代号:"+xhr.status+",错误信息:"+xhr.statusText);

61         }

62     }

63 }

64 

65 //调用ajax

66 var object={

67         method:"get",

68         url:"demo.php",

69         async:false,

70         data:{

71             name:"liu",

72             age:25

73             },

74         success:function (text){

75                    console.log(text);

76                 }

77         };

78 document.addEventListener("click",function(){

79     console.log(ajax(object));

80 },false);

 

你可能感兴趣的:(Ajax)