forked from devcem/Playcanvas-UI-Components
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Fetcher.js
60 lines (50 loc) · 1.75 KB
/
Fetcher.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
var Fetcher = pc.createScript('fetcher');
Fetcher.attributes.add('URL', { type : 'string' });
Fetcher.attributes.add('data', { type : 'string' });
Fetcher.attributes.add('success', { type : 'string' });
Fetcher.attributes.add('error', { type : 'string' });
Fetcher.attributes.add('success', { type : 'string' });
Fetcher.prototype.initialize = function() {
this.onFetch();
this.app.on('Fetcher:' + this.entity.name, this.onFetch, this);
};
Fetcher.prototype.onResult = function(data) {
if(data){
if(data.success === true){
this.onSuccess(data.result);
}else{
this.onError(data.message);
}
}else{
this.onError('An error occured!');
}
};
Fetcher.prototype.onSuccess = function(data) {
if(this.success){
this.app.fire(this.success, data);
}
};
Fetcher.prototype.onError = function(data) {
if(this.error){
this.app.fire(this.error, data);
}
};
Fetcher.prototype.onFetch = function() {
this.fetch(this.URL, this.data, this.onResult.bind(this));
};
Fetcher.prototype.fetch = function(URL, data, success) {
var params = typeof data == 'string' ? data : Object.keys(data).map(
function(k){
return encodeURIComponent(k) + '=' + encodeURIComponent(data[k]);
}
).join('&');
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xhr.open('POST', URL);
xhr.onreadystatechange = function() {
if (xhr.readyState>3 && xhr.status==200) { success(JSON.parse(xhr.responseText)); }
};
//xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.withCredentials = true;
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(params);
};