ajax.js
1.48 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
class Ajax {
constructor(object){
if (typeof object !== "object")
this.data = {};
else
this.data = object;
this.http = new XMLHttpRequest();
}
default(){
if (("url" in this.data) === false) {
throw "URL not set";
}
if (("async" in this.data) === false){
this.data.async = true;
}
if ( "success" in this.data ){
this.http.onload = () => {
if (this.http.status == 200)
this.data.success(this.http.response);
}
}
if ( "error" in this.data ){
this.http.onerror = () => this.data.error(this.http.response);
}
if (this.data.async === false && "timeout" in this.data){
this.http.timeout = this.data.timeout;
if ("ontimeout" in this.data)
this.http.ontimeout = (this.data.ontimeout).bind(this.http);
}
}
post(){
this.default();
this.http.open("POST", this.data.url, this.data.async);
if ("contentType" in this.data) {
this.http.setRequestHeader('Content-Type', this.data.contentType);
}
if ("data" in this.data) {
this.http.send(JSON.stringify(this.data.data));
}
else {
this.http.send();
}
}
get(){
this.default();
if ("contentType" in this.data) {
this.http.setRequestHeader('Content-Type', this.data.contentType);
}
if ("data" in this.data) {
this.http.open("GET", this.data.url + "?" + this.data.data, this.data.async);
}
else {
this.http.open("GET", this.data.url, this.data.async);
}
this.http.send();
}
}