Built motion from commit 42b6453.|2.0.28
[motion2.git] / demo / agents / ajax.js
1 function Ajax() {}
2
3 Ajax.prototype.jsonpHandler = function(url, callback) {
4     var scripturl = url + ((url.indexOf("?") !== -1) ? "&" : "?") + "callback=" + callback;
5     document.write('<script src="' + scripturl + '"></script>');
6     return scripturl;
7 };
8
9 Ajax.prototype.request = function(method, url, fallback, options) {
10     var self = this,
11         options = options || {},
12         sf = options.success,
13         ef = options.error,
14         params = options.params;
15     if (options.jsonp) {
16         return self.jsonpHandler(url, options.jsonpCallback);
17     }
18     var xhr = new XMLHttpRequest();
19     if ("withCredentials" in xhr) {
20         xhr.open(method, url, true);
21     } else if (typeof XDomainRequest !== "undefined") {
22         xhr = new XDomainRequest();
23         xhr.open(method, url);
24     } else {
25         if (fallback === true) {
26             xhr.open(method, url, true);
27         } else {
28             xhr = null;
29             return xhr;
30         }
31     }
32     xhr.onreadystatechange = function(event) {
33         if (this.readyState === 4) {
34             if (this.status === 200 && sf) {
35                 sf(this.responseText);
36             } else {
37                 ef("Not OK. " + this.statusText);
38             }
39         }
40     };
41     xhr.onerror = function(data) {
42         if (ef) {
43             ef("ajax error " + this.statusText);
44         }
45     };
46     try {
47         xhr.withCredentials = true;
48         xhr.setRequestHeader("Authorization", 'Basic ' + btoa('admin:password'));
49         if (params) {
50             xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
51             xhr.send(params);
52         } else {
53             xhr.send();
54         }
55     } catch (e) {
56         if (ef) {
57             ef("error " + e.name + ": " + e.message);
58         }
59     }
60     return xhr;
61 };