-
Notifications
You must be signed in to change notification settings - Fork 2
/
xhr.js
113 lines (101 loc) · 3.05 KB
/
xhr.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/* $Id: xhr.js,v 1.0 2011/05/31 17:22:00 laudarch Exp $ */
/**
* complete asynchronous xmlhttprequest function
*/
var a$ = {
/**
* asychronous xmlhttprequest
*
* @param (string) url - url to open
* @param (array) options - defines method, callback, etc
* @return (boolean) false - return false on error
* @type (boolean)
*/
xhr:function( url, options)
{
var o = options ? options : {};
if (typeof options == "function") {
o = {};
o.callback = options;
}
var xhr = this.getxhr();
var method = o.method || 'get';
var restype = o.restype || 'text';
var async = o.async || false;
var params = o.data || null;
var i = 0;
var ret;
if (!xhr) return(false);
xhr.open(method, url, async);
if (o.headers) {
for (; i < o.headers.length; i++) {
xhr.setRequestHeader(o.headers[i].name, o.headers[i].value);
}
}
if ((/POST/i).test(method)) {
xhr.setRequestHeader("Content-type",
"application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", params.length);
xhr.setRequestHeader("Accept", "*/*");
xhr.setRequestHeader("Connection", "close");
}
if ((/POST/i).test(method)) {
xhr.send(params);
} else {
xhr.send(null);
}
handleResp = (o.callback != null) ?
o.callback :
function(rt) {alert(rt);};
handleError = (o.error && typeof(o.error) == 'function') ?
o.error :
function(e) {alert(e);};
/**
* internal handler
*/
function hdl()
{
if (xhr.readyState == 4) {
delete(xhr);
if (xhr.status===0 || xhr.status==200) {
if (/plain/i.test(restype)) ret = xhr.responseText;
if (/text/i.test(restype)) ret = xhr.responseText;
if (/xml/i.test(restype)) ret = xhr.responseXML;
if (/json/i.test(restype)) ret = xhr.responseText;
handleResp(ret);
}
if ((/^[4(5|0)]/).test(xhr.status))
handleError(xhr.responseText);
}
}
if (async) {
xhr.onreadystatechange = hdl;
}
if (!async) hdl();
return (this);
},
/**
* get XMLHttpRequest Object
*
* @return (object) xmlhttprequest object
* @type (object)
*/
getxhr:function()
{
var req = false;
try {
req = new XMLHttpRequest();
} catch (e1) {
try {
req = new ActiveObject("Msxml2.XMLHTTP");
} catch (e2) {
try {
req = new ActiveObject("Microsoft.XMLHTTP");
} catch (e3) {
return (false);
}
}
}
return (req);
}
};