This repository has been archived by the owner on Aug 21, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
AjaxRequest.js
89 lines (76 loc) · 2.78 KB
/
AjaxRequest.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
define(function(require, exports, module) {
var OptionsManager = require('famous/core/OptionsManager');
function AjaxRequest() {
this.response = Q.defer();
this.options = Object.create(AjaxRequest.DEFAULT_OPTIONS);
this._optionsManager = new OptionsManager(this.options);
};
AjaxRequest.DEFAULT_OPTIONS = {
method: 'GET',
url: undefined,
type: undefined,
params: undefined,
timeout: 5000
};
AjaxRequest.prototype.get = function get(options) {
_makeRequest.call(this, options);
return this.response.promise;
};
AjaxRequest.prototype.post = function post(options) {
this.options.post = 'POST';
_makeRequest.call(this, options);
return this.response.promise;
};
// make your own helper methods!
// AjaxRequest.prototype.loginRequest = function loginRequest(options) {
// this.options.method = 'POST';
// this.options.type = 'application/json';
// this.options.url = '/auth/login';
// _makeRequest.call(this, options);
// return this.response.promise;
// };
function _makeRequest(options) {
this._optionsManager.setOptions(options);
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
var req = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
try {
var req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
var req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {};
};
};
if (!req) {
console.log('Unable to create an XMLHTTP instance');
return false;
};
// .open(method, url, async)
req.open(this.options.method, this.options.url, true);
var ctx = this;
req.onreadystatechange = function() {
try {
if (req.readyState === 4) {
if (req.status) {
ctx.response.resolve(req);
} else {
ctx.response.reject("HTTP " + req.status + " for " + ctx.options.url);
};
};
} catch (e) {
console.log('Exception: ' + e.description);
};
};
req.setRequestHeader('Content-Type', this.options.type);
this.options.timeout && setTimeout(this.response.reject, this.options.timeout);
if (this.options.params) {
if (this.options.type === 'application/json') {
req.send(JSON.stringify(this.options.params));
} else {
req.send(this.options.params);
};
} else req.send();
};
module.exports = AjaxRequest;
});