forked from RubyLouvre/avalon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
avalon.sync.js
76 lines (73 loc) · 3.19 KB
/
avalon.sync.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
(function($) {
var DOC = document,
r20 = /%20/g,
rCRLF = /\r?\n/g,
encode = encodeURIComponent,
decode = decodeURIComponent,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg,
// IE的换行符不包含 \r
rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rquery = /\?/,
rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,
//在IE下如果重置了document.domain,直接访问window.location会抛错,但用document.URL就ok了
//http://www.cnblogs.com/WuQiang/archive/2012/09/21/2697474.html
curl = DOC.URL,
segments = rurl.exec(curl.toLowerCase()) || [],
isLocal = rlocalProtocol.test(segments[1]),
//http://www.cnblogs.com/rubylouvre/archive/2010/04/20/1716486.html
s = ["XMLHttpRequest", "ActiveXObject('Msxml2.XMLHTTP.6.0')",
"ActiveXObject('Msxml2.XMLHTTP.3.0')", "ActiveXObject('Msxml2.XMLHTTP')"];
if (!"1" [0]) { //判定IE67
s[0] = location.protocol === "file:" ? "!" : s[0];
}
for (var i = 0, axo; axo = s[i++]; ) {
try {
if (eval("new " + axo)) {
$.xhr = new Function("return new " + axo);
break;
}
} catch (e) {
}
}
var accepts = {
xml: "application/xml, text/xml",
html: "text/html",
text: "text/plain",
json: "application/json, text/javascript",
script: "text/javascript, application/javascript",
"*": ["*/"] + ["*"] //避免被压缩掉
},
defaults = {
type: "GET",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
async: true,
jsonp: "callback"
};
//将data转换为字符串,type转换为大写,添加hasContent,crossDomain属性,如果是GET,将参数绑在URL后面
function setOptions(opts) {
opts = $.mix({}, defaults, opts);
if (typeof opts.crossDomain !== "boolean") { //判定是否跨域
var parts = rurl.exec(opts.url.toLowerCase());
opts.crossDomain = !!(parts && (parts[1] !== segments[1] || parts[2] !== segments[2] || (parts[3]
|| (parts[1] === "http:" ? 80 : 443)) !== (segments[3] || (segments[1] === "http:" ? 80 : 443))));
}
if (opts.data && typeof opts.data !== "object") {
$.error("data必须为对象");
}
var querystring = $.param(opts.data);
opts.querystring = querystring || "";
opts.url = opts.url.replace(/#.*$/, "").replace(/^\/\//, segments[1] + "//");
opts.type = opts.type.toUpperCase();
opts.hasContent = !rnoContent.test(opts.type); //是否为post请求
if (!opts.hasContent) {
if (querystring) { //如果为GET请求,则参数依附于url上
opts.url += (rquery.test(opts.url) ? "&" : "?") + querystring;
}
if (opts.cache === false) { //添加时间截
opts.url += (rquery.test(opts.url) ? "&" : "?") + "_time=" + (+new Date);
}
}
return opts;
}
})(avalon)