-
Notifications
You must be signed in to change notification settings - Fork 1
/
backbone.tv.xhr-worker.js
43 lines (37 loc) · 1.03 KB
/
backbone.tv.xhr-worker.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
var ajax = function(opts, callback) {
var xhr = new XMLHttpRequest();
var method = opts.method.toUpperCase();
var url = opts.url;
var async = ('async' in opts) ? opts.async : false;
var headers = opts.headers;
var data = opts.data || null;
xhr.open(opts.method, opts.url, opts.async)
if (headers) {
for (var key in headers) {
xhr.setRequestHeader(key, headers[key]);
}
}
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var status = function(s) {
return ((s >= 200 && s < 300) || s == 304) ? 'success' : 'error';
}
callback({
status: status(xhr.status),
statusCode: xhr.status,
textStatus: xhr.statusText,
responseText: xhr.responseText,
xhr:JSON.stringify(xhr)
});
}
};
xhr.send(data);
};
self.addEventListener('message', function(message) {
var options = message.data;
ajax(options, function(response) {
options.type = 'response';
options.response = response;
postMessage(options);
});
}, false);