-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAjax-2.js
More file actions
40 lines (40 loc) · 1.12 KB
/
Ajax-2.js
File metadata and controls
40 lines (40 loc) · 1.12 KB
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
//单例封装
//闭包
//返回一个对象引用
Ajax = function(){
function request(url,param){
function fn(){};//返回对象的引用
var async = param.async||false,
method = param.method||'GET',
data = param.data||'null',
encode = param.encode||'utf-8',
success = param.success||fn;
failure = param.failure||fn;
method = method.toUpperCase();
var xhr = window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject();
//onreadystatechange()在open()之前调用为了确保浏览器的兼容性
xhr.onreadystatechange = function(xhr,success,failure){
_onreadystatechange(xhr,success,failure);
};
// xhr.setRequestHeader("x-Content-Security-Policy;","default-src");
xhr.open(method,url,async);
if(method == 'GET'&&data){
url += (url.indexOf('?')==-1?'?':'&')+data;
data =null;
}
if(method == 'POST'){
xhr.setRequestHeader("Content-type","x-www-form-urlencode;");
}
xhr.send(data);
function _onreadystatechange(xhr,success,failure){
if(xhr.readyState == 4){
if(xhr.status == 200){
success(xhr);
}else{
failure(xhr);
}
}
}
};
return {request:request};
}