-
Notifications
You must be signed in to change notification settings - Fork 108
/
ajax.js
167 lines (158 loc) · 6.98 KB
/
ajax.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
(function(window,undefined) {
function ajax(options) {
//编码数据
function setData() {
//设置对象的遍码
function setObjData(data, parentName) {
function encodeData(name, value, parentName) {
var items = [];
name = parentName === undefined ? name : parentName + "[" + name + "]";
if (typeof value === "object" && value !== null) {
items = items.concat(setObjData(value, name));
} else {
name = encodeURIComponent(name);
value = encodeURIComponent(value);
items.push(name + "=" + value);
}
return items;
}
var arr = [],value;
if (Object.prototype.toString.call(data) == '[object Array]') {
for (var i = 0, len = data.length; i < len; i++) {
value = data[i];
arr = arr.concat(encodeData( typeof value == "object"?i:"", value, parentName));
}
} else if (Object.prototype.toString.call(data) == '[object Object]') {
for (var key in data) {
value = data[key];
arr = arr.concat(encodeData(key, value, parentName));
}
}
return arr;
};
//设置字符串的遍码,字符串的格式为:a=1&b=2;
function setStrData(data) {
var arr = data.split("&");
for (var i = 0, len = arr.length; i < len; i++) {
name = encodeURIComponent(arr[i].split("=")[0]);
value = encodeURIComponent(arr[i].split("=")[1]);
arr[i] = name + "=" + value;
}
return arr;
}
if (data) {
if (typeof data === "string") {
data = setStrData(data);
} else if (typeof data === "object") {
data = setObjData(data);
}
data = data.join("&").replace("/%20/g", "+");
//若是使用get方法或JSONP,则手动添加到URL中
if (type === "get" || dataType === "jsonp") {
url += url.indexOf("?") > -1 ? (url.indexOf("=") > -1 ? "&" + data : data) : "?" + data;
}
}
}
// JSONP
function createJsonp() {
var script = document.createElement("script"),
timeName = new Date().getTime() + Math.round(Math.random() * 1000),
callback = "JSONP_" + timeName;
window[callback] = function(data) {
clearTimeout(timeout_flag);
document.body.removeChild(script);
success(data);
}
script.src = url + (url.indexOf("?") > -1 ? "&" : "?") + "callback=" + callback;
script.type = "text/javascript";
document.body.appendChild(script);
setTime(callback, script);
}
//设置请求超时
function setTime(callback, script) {
if (timeOut !== undefined) {
timeout_flag = setTimeout(function() {
if (dataType === "jsonp") {
delete window[callback];
document.body.removeChild(script);
} else {
timeout_bool = true;
xhr && xhr.abort();
}
console.log("timeout");
}, timeOut);
}
}
// XHR
function createXHR() {
//由于IE6的XMLHttpRequest对象是通过MSXML库中的一个ActiveX对象实现的。
//所以创建XHR对象,需要在这里做兼容处理。
function getXHR() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else {
//遍历IE中不同版本的ActiveX对象
var versions = ["Microsoft", "msxm3", "msxml2", "msxml1"];
for (var i = 0; i < versions.length; i++) {
try {
var version = versions[i] + ".XMLHTTP";
return new ActiveXObject(version);
} catch (e) {}
}
}
}
//创建对象。
xhr = getXHR();
xhr.open(type, url, async);
//设置请求头
if (type === "post" && !contentType) {
//若是post提交,则设置content-Type 为application/x-www-four-urlencoded
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
} else if (contentType) {
xhr.setRequestHeader("Content-Type", contentType);
}
//添加监听
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (timeOut !== undefined) {
//由于执行abort()方法后,有可能触发onreadystatechange事件,
//所以设置一个timeout_bool标识,来忽略中止触发的事件。
if (timeout_bool) {
return;
}
clearTimeout(timeout_flag);
}
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
success(xhr.responseText);
} else {
error(xhr.status, xhr.statusText);
}
}
};
//发送请求
xhr.send(type === "get" ? null : data);
setTime(); //请求超时
}
var url = options.url || "", //请求的链接
type = (options.type || "get").toLowerCase(), //请求的方法,默认为get
data = options.data || null, //请求的数据
contentType = options.contentType || "", //请求头
dataType = options.dataType || "", //请求的类型
async = options.async === undefined ? true : options.async, //是否异步,默认为true.
timeOut = options.timeOut, //超时时间。
before = options.before || function() {}, //发送之前执行的函数
error = options.error || function() {}, //错误执行的函数
success = options.success || function() {}; //请求成功的回调函数
var timeout_bool = false, //是否请求超时
timeout_flag = null, //超时标识
xhr = null; //xhr对角
setData();
before();
if (dataType === "jsonp") {
createJsonp();
} else {
createXHR();
}
}
window.ajax = ajax;
})(window);