forked from alexyoung/turing.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
turing.net.js
254 lines (222 loc) · 6.62 KB
/
turing.net.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
/*!
* Turing Net
* Copyright (C) 2010-2011 Alex R. Young
* MIT Licensed
*/
/**
* The Turing Net module (Ajax).
*/
(function() {
var net = {};
/**
* Ajax request options:
*
* - `method`: {String} HTTP method - GET, POST, etc.
* - `success`: {Function} A callback to run when a request is successful
* - `error`: {Function} A callback to run when the request fails
* - `asynchronous`: {Boolean} Defaults to asynchronous
* - `postBody`: {String} The HTTP POST body
* - `contentType`: {String} The content type of the request, default is `application/x-www-form-urlencoded`
*
*/
function xhr() {
if (typeof XMLHttpRequest !== 'undefined' && (window.location.protocol !== 'file:' || !window.ActiveXObject)) {
return new XMLHttpRequest();
} else {
try {
return new ActiveXObject('Msxml2.XMLHTTP.6.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP.3.0');
} catch(e) { }
try {
return new ActiveXObject('Msxml2.XMLHTTP');
} catch(e) { }
}
return false;
}
function successfulRequest(request) {
return (request.status >= 200 && request.status < 300) ||
request.status == 304 ||
(request.status == 0 && request.responseText);
}
/**
* Serialize JavaScript for HTTP requests.
*
* @param {Object} object An Array or Object
* @returns {String} A string suitable for a GET or POST request
*/
net.serialize = function(object) {
if (!object) return;
var results = [];
for (var key in object) {
results.push(encodeURIComponent(key) + '=' + encodeURIComponent(object[key]));
}
return results.join('&');
};
/**
* JSON.parse support can be inferred using `turing.detect('JSON.parse')`.
*/
turing.addDetectionTest('JSON.parse', function() {
return window.JSON && window.JSON.parse;
});
/**
* Parses JSON represented as a string.
*
* @param {String} string The original string
* @returns {Object} A JavaScript object
*/
net.parseJSON = function(string) {
if (typeof string !== 'string' || !string) return null;
string = string.trim();
return turing.detect('JSON.parse') ?
window.JSON.parse(string) :
(new Function('return ' + string))();
};
function ajax(url, options) {
var request = xhr();
function respondToReadyState(readyState) {
if (request.readyState == 4) {
if (request.getResponseHeader('content-type') === 'application/json')
request.responseJSON = net.parseJSON(request.responseText);
if (successfulRequest(request)) {
if (options.success) options.success(request);
} else {
if (options.error) options.error(request);
}
}
}
// Set the HTTP headers
function setHeaders() {
var defaults = {
'Accept': 'text/javascript, application/json, text/html, application/xml, text/xml, */*',
'Content-Type': 'application/x-www-form-urlencoded'
};
/**
* Merge headers with defaults.
*/
for (var name in defaults) {
if (!options.headers.hasOwnProperty(name))
options.headers[name] = defaults[name];
}
for (var name in options.headers) {
request.setRequestHeader(name, options.headers[name]);
}
}
if (typeof options === 'undefined') options = {};
options.method = options.method ? options.method.toLowerCase() : 'get';
options.asynchronous = options.asynchronous || true;
options.postBody = options.postBody || '';
request.onreadystatechange = respondToReadyState;
request.open(options.method, url, options.asynchronous);
options.headers = options.headers || {};
if (options.contentType) {
options.headers['Content-Type'] = options.contentType;
}
if (typeof options.postBody !== 'string') {
// Serialize JavaScript
options.postBody = net.serialize(options.postBody);
}
setHeaders();
try {
request.send(options.postBody);
} catch (e) {
if (options.error) {
options.error();
}
}
return request;
}
function JSONPCallback(url, success, failure) {
var self = this;
this.url = url;
this.methodName = '__turing_jsonp_' + parseInt(new Date().getTime());
this.success = success;
this.failure = failure;
function runCallback(json) {
self.success(json);
self.teardown();
}
window[this.methodName] = runCallback;
}
JSONPCallback.prototype.run = function() {
this.scriptTag = document.createElement('script');
this.scriptTag.id = this.methodName;
this.scriptTag.src = this.url.replace('{callback}', this.methodName);
document.body.appendChild(this.scriptTag);
}
JSONPCallback.prototype.teardown = function() {
window[this.methodName] = null;
delete window[this.methodName];
if (this.scriptTag) {
document.body.removeChild(this.scriptTag);
}
}
/**
* An Ajax GET request.
*
* turing.net.get('/url', {
* success: function(request) {
* }
* });
*
* @param {String} url The URL to request
* @param {Object} options The Ajax request options
* @returns {Object} The Ajax request object
*/
net.get = function(url, options) {
options.method = 'get';
return ajax(url, options);
};
/**
* An Ajax POST request.
*
*
* turing.net.post('/url', {
* postBody: 'params',
* success: function(request) {
* }
* });
*
* @param {String} url The URL to request
* @param {Object} options The Ajax request options (`postBody` may come in handy here)
* @returns {Object} The Ajax request object
*/
net.post = function(url, options) {
options.method = 'post';
return ajax(url, options);
};
/**
* A jsonp request. Example:
*
* var url = 'http://feeds.delicious.com/v1/json/';
* url += 'alex_young/javascript?callback={callback}';
*
* turing.net.jsonp(url, {
* success: function(json) {
* console.log(json);
* }
* });
*
* @param {String} url The URL to request
* @param {Object} options The Ajax request options
*/
net.jsonp = function(url, options) {
if (typeof options === 'undefined') options = {};
var callback = new JSONPCallback(url, options.success, options.failure);
callback.run();
};
/**
* The Ajax methods are mapped to the `turing` object:
*
* turing.get();
* turing.post();
* turing.json();
*
*/
turing.get = net.get;
turing.post = net.post;
turing.jsonp = net.jsonp;
net.ajax = ajax;
turing.net = net;
})();