Ajax封装

 1 //封装
 2 
 3 function obj2str(data) {
 4     /*
 5  6     "username":"inj",
 7     "userpwd":"123",
 8     "t":"1234554212"
 9 10      */
11     data.t = new Date().getTime();
12     var res = [];
13     for (var key in data){
14         //如果URL有中文会转换为指定格式---encodeURIComponent
15         //data[key]就是value
16         res.push(encodeURIComponent(key) + "=" + encodeURIComponent(data[key]));//[username=inj,userpwd=123];
17     }
18     return res.join("&");//username=inj&userpwd=123
19 //    join将数组转换为字符串
20 }
21 
22 function  ajax(option) {
23     // 0.将对象转换为字符串
24     var str = obj2str(option.data);//key=value&key=value;
25     // 1.创建异步对象
26     var timer;
27     var xmlhttp = new XMLHttpRequest();
28     // 2.设置请求方式和地址
29 
30     //URL设置每次都不一样的,兼容IE
31     //URL不能是中文
32     //转成小写
33     //请求方式的类型GET,POST
34     if (option.type.toLowerCase() === "get"){
35     xmlhttp.open(option.type, option.url+"?"+str, true);
36     // 3.发送请求
37     xmlhttp.send();
38     }else{
39         xmlhttp.open(option.type,option.url,true);
40         //注意:放在open和send中间
41         xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
42         xmlhttp.send(str);
43     }
44 
45     // 4.监听状态的变化
46     xmlhttp.onreadystatechange = function (ev2) {
47         //4:请求已完成,且响应就绪
48         if (xmlhttp.readyState === 4){
49             clearInterval(timer);
50             if (xmlhttp.status < 300 && xmlhttp.status >= 200 || xmlhttp.status ===304){
51                 // console.log("接收到");
52                 option.success(xmlhttp);
53             }
54             else {
55                 // console.log("没接收到");
56                 option.error(xmlhttp);
57             }
58         }
59     }
60 //    判断外界是否传入了超时时间
61     if (option.timeout){
62         timer = setInterval(function () {
63             //中断请求
64             xmlhttp.abort();
65             clearInterval(timer);
66         },option.timeout);
67     }
68 }
原文地址:https://www.cnblogs.com/monica4/p/11155835.html