-
Notifications
You must be signed in to change notification settings - Fork 0
/
ajax.js
76 lines (60 loc) · 1.69 KB
/
ajax.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
class Ajax {
constructor(config) {
this.method = config.method
this.url = config.url
this.params = config.params
this.fragment = config.fragment
this.headers = config.headers
this.xhr = Ajax._createXHR()
this.uri = Ajax._parseQuery(this.url, this.params, this.fragment)
const success = config.success, error = config.error
if (this.headers) {
// Set the request headers.
Object.keys(this.headers).forEach(function(headerKey) {
const headerValue = this.headers[headerKey]
this.xhr.setRequestHeader(headerKey, headerValue)
})
}
this.xhr.open(this.method, this.uri, true)
this.xhr.send()
const that = this
this.xhr.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
const res = this.responseText
const contentType = this.getResponseHeader('Content-Type')
if (contentType.includes('application/json')) {
res = JSON.parse(res)
}
if (success) {
success(res)
}
} else {
if (error && this.readyState === 4) {
error(this.status, this.getAllResponseHeaders())
}
}
}
}
static _createXHR() {
try {
return new window.XMLHttpRequest()
} catch (err) {
throw new Error('Error creating the XMLHttpRequest object')
}
}
static _parseQuery(url, params, fragment) {
let uri = url
if (params) {
uri += '?'
for (let key in params) {
uri += `${key}=${params[key]}&`
}
uri = uri.replace(/&$/, '')
}
if (fragment) {
uri += `#${fragment}`
}
return uri
}
}
module.exports = Ajax