-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRequestController.js
More file actions
112 lines (94 loc) · 2.23 KB
/
RequestController.js
File metadata and controls
112 lines (94 loc) · 2.23 KB
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
class RequestController {
constructor() {
this.url = null;
this.method_list = ["GET","POST","PUT"];
this.method = "GET";
this.content_type = "application/x-www-form-urlencoded";
}
set_url (url){
this.url = url;
}
set_method (method){
if (!this.method_list.includes(method))
return false;
this.method = method;
}
send(params,callback = (x)=>{} ){
if (this.url == null ) { return; }
switch(this.method) {
case "GET":
this.get(params,(x)=>{
callback(x);
});
break;
case "POST":
this.post(params,(x)=>{
callback(x);
});
break;
case "PUT":
this.put(params,(x)=>{
callback(x);
});
break;
case "DELETE":
this.delete(params,(x)=>{
callback(x);
});
break;
default:
console.log("method is no vailate");
}
}
get(params,callback = (x)=>{}){
//foo=bar&lorem=ipsum
let self = this;
let url = this.url + "?" + params;
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onload = function () {
callback(this.responseText);
};
xhr.onerror = function() {
self.on_error();
};
xhr.send();
}
post(params,callback = (x)=>{}){
this.xml_http_request("POST",this.url,params,(x)=>{
callback(x);
});
}
put(params,callback = (x)=>{}){
this.xml_http_request("PUT",this.url,params,(x)=>{
callback(x);
});
}
delete(params,callback = (x)=>{}){
this.xml_http_request("DELETE",this.url,params,(x)=>{
callback(x);
});
}
set_content_type(c) {
this.content_type = c;
}
xml_http_request(method,url,params = "",callback = (x)=>{}){
var xhr = new XMLHttpRequest();
xhr.open(method, url , true);
//Send the proper header information along with the request
xhr.setRequestHeader("Content-type", this.content_type);
xhr.onreadystatechange = function() {//Call a function when the state changes.
if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
callback(this.responseText);
}
}
let self = this;
xhr.onerror = function() {
self.on_error();
};
xhr.send(params);
}
on_error () {
alert('Some Error Occurs, Try to install the extentison');
}
}