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
|
KB.http.request = function (method, url, headers, body) {
var successCallback = function() {};
var errorCallback = function() {};
function parseResponse(request) {
try {
return JSON.parse(request.responseText);
} catch (e) {
return request.responseText;
}
}
this.execute = function () {
var request = new XMLHttpRequest();
request.open(method, url, true);
request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
for (var header in headers) {
if (headers.hasOwnProperty(header)) {
request.setRequestHeader(header, headers[header]);
}
}
request.onerror = function() {
errorCallback();
};
request.onreadystatechange = function() {
if (request.readyState === XMLHttpRequest.DONE) {
var response = parseResponse(request);
if (request.status === 200) {
successCallback(response);
} else {
errorCallback(response);
}
}
};
request.send(body);
return this;
};
this.success = function (callback) {
successCallback = callback;
return this;
};
this.error = function (callback) {
errorCallback = callback;
return this;
};
};
KB.http.get = function (url) {
return (new KB.http.request('GET', url)).execute();
};
KB.http.postJson = function (url, body) {
var headers = {
'Content-Type': 'application/json',
'Accept': 'application/json'
};
return (new KB.http.request('POST', url, headers, JSON.stringify(body))).execute();
};
|