1 import params
from "../parameters"; //for server URL
3 // From JSON (encoded string values!) to "arg1=...&arg2=..."
4 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 // data, error: optional
14 export function ajax(url
, method
, data
, success
, error
)
16 let xhr
= new XMLHttpRequest();
17 if (typeof(data
) === "function") //no data
24 error
= errmsg
=> { alert(errmsg
); };
26 xhr
.onreadystatechange = function() {
27 if (this.readyState
== 4 && this.status
== 200)
30 let res_json
= JSON
.parse(xhr
.responseText
);
34 error(res_json
.errmsg
);
36 // Plain text (e.g. for rules retrieval)
37 success(xhr
.responseText
);
42 if (["GET","DELETE"].includes(method
) && !!data
)
44 // Append query params to URL
45 url
+= "/?" + toQueryString(data
);
47 xhr
.open(method
, params
.serverUrl
+ url
, true);
48 xhr
.setRequestHeader('X-Requested-With', "XMLHttpRequest");
49 if (["POST","PUT"].includes(method
))
51 xhr
.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
52 xhr
.send(JSON
.stringify(data
));