-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheasyhttp.js
84 lines (59 loc) · 1.76 KB
/
easyhttp.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
// ES5 Object Oriented HTTP Library using Ajax, XHR Object, and Callbacks
/**
* EasyHTTP Library
* Library for making HTTP Requests
*
* @version 1.0.0
* @author Joseph Brown
* @license none
*
**/
function easyHTTP(){
this.http = new XMLHttpRequest();
}
// Make an HTTP GET Request
easyHTTP.prototype.get = function(url, callback){
this.http.open('GET', url, true);
let self = this; // Set another variable for this, that way we can capture it in the scope of the function below
this.http.onload = function(){
if(self.http.status === 200){
callback(null, self.http.responseText);
} else{
callback('Error: ' + self.http.status);
}
}
this.http.send();
}
// Make an HTTP POST Request
easyHTTP.prototype.post = function(url, data, callback){
this.http.open('POST', url, true);
this.http.setRequestHeader('Content-type', 'application/json');
let self = this;
this.http.onload = function(){
callback(null, self.http.responseText);
}
this.http.send(JSON.stringify(data));
}
// Make an HTTP PUT Request
easyHTTP.prototype.put = function(url, data, callback){
this.http.open('PUT', url, true);
this.http.setRequestHeader('Content-type', 'application/json');
let self = this;
this.http.onload = function(){
callback(null, self.http.responseText);
}
this.http.send(JSON.stringify(data));
}
// Make an HTTP DELETE Request
easyHTTP.prototype.delete = function(url, callback){
this.http.open('DELETE', url, true);
let self = this;
this.http.onload = function(){
if(self.http.status === 200){
callback(null, 'Post Deleted');
} else{
callback('Error: ' + self.http.status);
}
}
this.http.send();
}