1 // From JSON (encoded string values!) to "arg1=...&arg2=..."
2 function toQueryString(data
)
5 Object
.keys(data
).forEach(k
=> {
6 data_str
+= k
+ "=" + encodeURIComponent(data
[k
]) + "&";
8 return data_str
.slice(0, -1); //remove last "&"
11 // data, error: optional
12 export function ajax(url
, method
, data
, success
, error
)
14 let xhr
= new XMLHttpRequest();
15 if (typeof(data
) === "function") //no data
22 error
= errmsg
=> { alert(errmsg
); };
24 xhr
.onreadystatechange = function() {
25 if (this.readyState
== 4 && this.status
== 200)
28 let res_json
= JSON
.parse(xhr
.responseText
);
32 error(res_json
.errmsg
);
34 // Plain text (e.g. for rules retrieval)
35 success(xhr
.responseText
);
40 if (["GET","DELETE"].includes(method
) && !!data
)
42 // Append query params to URL
43 url
+= "/?" + toQueryString(data
);
45 xhr
.open(method
, url
, true);
46 xhr
.setRequestHeader('X-Requested-With', "XMLHttpRequest");
47 if (["POST","PUT"].includes(method
))
49 xhr
.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
50 xhr
.send(JSON
.stringify(data
));