forked from ded/reqwest
/
reqwest.js
256 lines (224 loc) · 6.45 KB
/
reqwest.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
/*!
* Reqwest! A x-browser general purpose XHR connection manager
* copyright Dustin Diaz 2011
* https://github.com/ded/reqwest
* license MIT
*/
!function (window) {
var twoHundo = /^20\d$/,
doc = document,
byTag = 'getElementsByTagName',
head = doc[byTag]('head')[0],
xhr = ('XMLHttpRequest' in window) ?
function () {
return new XMLHttpRequest();
} :
function () {
return new ActiveXObject('Microsoft.XMLHTTP');
};
var uniqid = 0;
// data stored by the most recent JSONP callback
var lastValue;
function readyState(o, success, error) {
return function () {
if (o && o.readyState == 4) {
if (twoHundo.test(o.status)) {
success(o);
} else {
error(o);
}
}
};
}
function setHeaders(http, options) {
var headers = options.headers || {};
headers.Accept = 'text/javascript, text/html, application/xml, text/xml, */*';
headers['X-Requested-With'] = headers['X-Requested-With'] || 'XMLHttpRequest';
if (options.data) {
headers['Content-type'] = 'application/x-www-form-urlencoded';
for (var h in headers) {
headers.hasOwnProperty(h) && http.setRequestHeader(h, headers[h], false);
}
}
}
function getCallbackName(o) {
var callbackVar = o.jsonpCallback || "callback";
if (o.url.slice(-(callbackVar.length + 2)) == (callbackVar + "=?")) {
// Generate a guaranteed unique callback name
var callbackName = "reqwest_" + uniqid++;
// Replace the ? in the URL with the generated name
o.url = o.url.substr(0, o.url.length - 1) + callbackName;
return callbackName;
} else {
// Find the supplied callback name
var regex = new RegExp(callbackVar + "=([\\w]+)");
return o.url.match(regex)[1];
}
}
// Store the data returned by the most recent callback
function generalCallback(data) {
lastValue = data;
}
function getRequest(o, fn, err) {
if (o.type == 'jsonp') {
var script = doc.createElement('script');
// Add the global callback
window[getCallbackName(o)] = generalCallback;
// Setup our script element
script.type = "text/javascript";
script.src = o.url;
script.async = true;
var onload = function () {
// Call the user callback with the last value stored
// and clean up values and scripts.
o.success && o.success(lastValue);
lastValue = undefined;
head.removeChild(script);
};
script.onload = onload;
// onload for IE
script.onreadystatechange = function () {
script.readyState == "loaded" && onload();
};
// Add the script to the DOM head
head.appendChild(script);
} else {
var http = xhr();
http.open(o.method || 'GET', typeof o == 'string' ? o : o.url, true);
setHeaders(http, o);
http.onreadystatechange = readyState(http, fn, err);
o.before && o.before(http);
http.send(o.data || null);
return http;
}
}
function Reqwest(o, fn) {
this.o = o;
this.fn = fn;
init.apply(this, arguments);
}
function setType(url) {
if (/\.json$/.test(url)) {
return 'json';
}
if (/\.jsonp$/.test(url)) {
return 'jsonp';
}
if (/\.js$/.test(url)) {
return 'js';
}
if (/\.html?$/.test(url)) {
return 'html';
}
if (/\.xml$/.test(url)) {
return 'xml';
}
return 'js';
}
function init(o, fn) {
this.url = typeof o == 'string' ? o : o.url;
this.timeout = null;
var type = o.type || setType(this.url), self = this;
fn = fn || function () {};
if (o.timeout) {
this.timeout = setTimeout(function () {
self.abort();
error();
}, o.timeout);
}
function complete(resp) {
o.complete && o.complete(resp);
}
function success(resp) {
o.timeout && clearTimeout(self.timeout) && (self.timeout = null);
var r = resp.responseText;
switch (type) {
case 'json':
resp = eval('(' + r + ')');
break;
case 'js':
resp = eval(r);
break;
case 'html':
resp = r;
break;
// default is the response from server
}
fn(resp);
o.success && o.success(resp);
complete(resp);
}
function error(resp) {
o.error && o.error(resp);
complete(resp);
}
this.request = getRequest(o, success, error);
}
Reqwest.prototype = {
abort: function () {
this.request.abort();
},
retry: function () {
init.call(this, this.o, this.fn);
}
};
function reqwest(o, fn) {
return new Reqwest(o, fn);
}
function enc(v) {
return encodeURIComponent(v);
}
function serial(el) {
var n = el.name;
// don't serialize elements that are disabled or without a name
if (el.disabled || !n) {
return '';
}
n = enc(n);
switch (el.tagName.toLowerCase()) {
case 'input':
switch (el.type) {
// silly wabbit
case 'reset':
case 'button':
case 'image':
case 'file':
return '';
case 'checkbox':
case 'radio':
return el.checked ? n + '=' + (el.value ? enc(el.value) : true) + '&' : '';
default: // text hidden password submit
return n + '=' + (el.value ? enc(el.value) : true) + '&';
}
break;
case 'textarea':
return n + '=' + enc(el.value) + '&';
case 'select':
// @todo refactor beyond basic single selected value case
return n + '=' + enc(el.options[el.selectedIndex].value) + '&';
}
return '';
}
reqwest.serialize = function (form) {
var inputs = form[byTag]('input'),
selects = form[byTag]('select'),
texts = form[byTag]('textarea');
return (v(inputs).chain().toArray().map(serial).value().join('') +
v(selects).chain().toArray().map(serial).value().join('') +
v(texts).chain().toArray().map(serial).value().join('')).replace(/&$/, '');
};
reqwest.serializeArray = function (f) {
for (var pairs = this.serialize(f).split('&'), i = 0, l = pairs.length, r = [], o; i < l; i++) {
pairs[i] && (o = pairs[i].split('=')) && r.push({name: o[0], value: o[1]});
}
return r;
};
var old = window.reqwest;
reqwest.noConflict = function () {
window.reqwest = old;
return this;
};
// defined as extern for Closure Compilation
// do not change to (dot) '.' syntax
window['reqwest'] = reqwest;
}(this);