-
Notifications
You must be signed in to change notification settings - Fork 0
/
Ajax.js
executable file
·91 lines (76 loc) · 1.78 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
/*
* By Chaney
*用法:
* $.ajax({
* url:url,
* data:{},
* success:function(){},
* error:function(){}
* })
* */
var $ = {};
$.ajax = ajax;
function formatUrl(json){
var arr = [];
json.t = Math.random();
for(var name in json){
arr.push(name + "=" + encodeURIComponent(json[name]));
}
return arr.join("&");
}
function ajax(options){
options = options || {};
if(!options.url)return ;
options.type = options.type || "get";
options.data = options.data || {};
options.timeout = options.timeout || 0;
options.dataType = optins.dataType || 'json';
var str = formatUrl(options.data);
//1 创建
if(window.XMLHttpRequest){
var xhr = new XMLHttpRequest();
} else {
var xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
if(options.type == "get"){
//2 连接
xhr.open("get",options.url + "?" + str,true);
//3 发送
xhr.send();
} else {
//2 连接
xhr.open("post",options.url,true);
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
//3 发送
xhr.send(str);
}
//4 接收
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){//完成
clearTimeout(timer);
if(xhr.status >= 200 && xhr.status < 300 || xhr.status == 304){
var data = xhr.responseText;
switch(options.dataType) {
case 'json':
if (window.JSON && JSON.parse) {
data = JSON.parse(data);
} else {
data = eval('(' + data + ')')
}
break;
case 'xml':
data = xhr.responseXML;
break;
}
options.success && options.success(data);
} else {
options.error && options.error(xhr.status);
}
}
};
if(options.timeout){
var timer = setTimeout(function(){
xhr.abort();
},options.timeout);
}
}