-
Notifications
You must be signed in to change notification settings - Fork 0
/
myajax.js
43 lines (41 loc) · 1.38 KB
/
myajax.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
//支持get,post,
function myajax(options){
options = options || {};
options.type = (options.type || "get").toUpperCase();
options.dataType = options.dataType || "json";
var params = formatParams(params);
// options.data =
var xhr;
// if(window.ActiveXObject){
// xhr = new window.ActiveXObject("Microsoft.XMLHTTP");
// }else {
xhr = new XMLHttpRequest();
// }
//接受xhr
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if(xhr.status >= 200 && xhr.status <= 300){
options.success && options.success(xhr.responseText, xhr.responseXML);
}else {
options.error && options.error(xhr.responseText,xhr.responseXML);
}
}
}
//发送
if(options.type = "GET"){
xhr.open('GET',options.url+'?'+params,true);
xhr.send(null);
}else if(options.type = "POST") {
xhr.open('POST',options.url);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(params);
}
function formatParams(data){
var arr = [];
for (var name in data) {
arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]));
}
arr.push(("v=" + Math.random()).replace(".", ""));
return arr.join("&");
}
};