-
Notifications
You must be signed in to change notification settings - Fork 0
/
ajax.js
102 lines (84 loc) · 2.52 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
var ktAjax = function (config) {
var defaultOption = {
url: "",
data: {},
type: "GET",
headers: {
},
success: function () { },
error: function () { },
complet: function () { }
}
//合并配置参数
var opt = extend(defaultOption, config);
/**
* 创建xmlhttprequest对象
*/
var xhr = function () {
var xmlhttprequest;
if (window.XMLHttpRequest) {
//IE7,IE8,firefox,MOailla,Safari,Opera等浏览器创建
xmlhttprequest = new XMLHttpRequest();
if (xmlhttprequest.overrideMineType) {
xmlhttprequest.overrideMineType("text/xml");
}
} else if (window.ActiveXObject) {
var activeName = ["MSML2.XMLHTTP", "Microsoft.XMLHTTP"];
for (var i = 0, len = activeName.length; i < len; i++) {
try {
xmlhttprequest = new ActiveXObject(activeName[i]);
}
catch (e) {
console.error(e);
}
}
}
if (!xmlhttprequest) {
console.error("XMLHttpRequest对象创建失败!");
} else {
this.xhr = new XMLHttpRequest();
}
}
/**
* 发送函数
*/
xhr.prototype.send = function (url) {
var xmlHR = this.xhr;
if (xmlHR) {
xmlHR.onreadystatechange = function () {
if (xmlHR.readyState === 4) {
if (xmlHR.status === 200) {
//请求成功
opt.success({ response: xmlHR.response });
} else {
//请求失败
opt.error({ response: xmlHR });
}
}
};
//添加头信息
var headers = opt.headers;
for (var name in headers) {
xmlHR.setRequestHeader(name, headers[name]);
}
//谷歌默认头信息 兼容火狐
xmlHR.setRequestHeader("Accept", "*");
if (opt.url) {
xmlHR.open(opt.type, opt.url, true);
}
xmlHR.send(opt.data);
}
}
/**
* 合并参数
* object1:默认对象
* object2:参数对象
*/
function extend(object1, object2) {
for (var name in object1) {
object1[name] = object2[name] || object1[name];
}
return object1;
}
return new xhr();
}