7d520ec8cc6a5e78b0387b61a4b9a15139b0a3dc
1 import params
from "../parameters"; //for server URL
2 import { store
} from "../store"; //for translations
4 // From JSON (encoded string values!) to "arg1=...&arg2=..."
5 function toQueryString(data
) {
7 Object
.keys(data
).forEach(k
=> {
8 data_str
+= k
+ "=" + encodeURIComponent(data
[k
]) + "&";
10 return data_str
.slice(0, -1); //remove last "&"
13 // TODO: use this syntax https://stackoverflow.com/a/29823632 ?
14 // data, success, error: optional
15 export function ajax(url
, method
, options
) {
16 options
= options
|| {};
17 const data
= options
.data
|| {};
18 // By default, do nothing on success and print errors:
20 options
.success
= () => {};
22 options
.error
= (errmsg
) => {
23 alert(store
.state
.tr
[errmsg
] || errmsg
);
26 if (["GET", "DELETE"].includes(method
) && !!data
)
27 // Append query params to URL
28 url
+= "/?" + toQueryString(data
);
30 "Content-Type": "application/json;charset=UTF-8",
31 "X-Requested-With": "XMLHttpRequest"
37 if (["POST", "PUT"].includes(method
))
38 fetchOptions
["body"] = JSON
.stringify(data
);
40 !!options
.credentials
||
41 (method
!= "GET" && !options
.nocredentials
)
43 fetchOptions
["credentials"] = params
.credentials
;
45 fetch(params
.serverUrl
+ url
, fetchOptions
)
46 .then(res
=> res
.json())
48 if (!json
.errmsg
&& !json
.errno
) options
.success(json
);
50 if (!!json
.errmsg
) options
.error(json
.errmsg
);
51 else options
.error(json
.code
+ ". errno = " + json
.errno
);