ajax.js
2.35 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
/**
* (c) 2010-2017 Christer Vasseng, Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
import H from '../parts/Globals.js';
/**
* @typedef {Object} AjaxSettings
* @property {String} url - The URL to call
* @property {('get'|'post'|'update'|'delete')} type - The verb to use
* @property {('json'|'xml'|'text'|'octet')} dataType - The data type expected
* @property {Function} success - Function to call on success
* @property {Function} error - Function to call on error
* @property {Object} data - The payload to send
* @property {Object} headers - The headers; keyed on header name
*/
/**
* Perform an Ajax call.
*
* @memberof Highcharts
* @param {AjaxSettings} - The Ajax settings to use
*
*/
H.ajax = function (attr) {
var options = H.merge(true, {
url: false,
type: 'GET',
dataType: 'json',
success: false,
error: false,
data: false,
headers: {}
}, attr),
headers = {
json: 'application/json',
xml: 'application/xml',
text: 'text/plain',
octet: 'application/octet-stream'
},
r = new XMLHttpRequest();
function handleError(xhr, err) {
if (options.error) {
options.error(xhr, err);
} else {
// Maybe emit a highcharts error event here
}
}
if (!options.url) {
return false;
}
r.open(options.type.toUpperCase(), options.url, true);
r.setRequestHeader(
'Content-Type',
headers[options.dataType] || headers.text
);
H.objectEach(options.headers, function (val, key) {
r.setRequestHeader(key, val);
});
r.onreadystatechange = function () {
var res;
if (r.readyState === 4) {
if (r.status === 200) {
res = r.responseText;
if (options.dataType === 'json') {
try {
res = JSON.parse(res);
} catch (e) {
return handleError(r, e);
}
}
return options.success && options.success(res);
}
handleError(r, r.responseText);
}
};
try {
options.data = JSON.stringify(options.data);
} catch (e) {}
r.send(options.data || true);
};