HLRTest/render/utils.js

63 lines
1.3 KiB
JavaScript
Raw Normal View History

2023-11-28 18:32:40 +01:00
"use strict";
function $(name) { return document.getElementById(name); }
function Tag(name, attrs, body, children) {
let elem = document.createElement(name);
if (body) {
elem.innerHTML = body;
}
for (let k in attrs) {
elem.setAttribute(k, attrs[k]);
}
for (let i in children) {
elem.appendChild(children[i]);
}
return elem;
}
function Text(text) {
return document.createTextNode(text);
}
function debounce(func, cancelFunc, timeout = 500) {
let timer;
return (...args) => {
cancelFunc();
clearTimeout(timer);
timer = setTimeout(() => { func.apply(this, args); }, timeout);
}
}
function sendRequest(method, path, query, body, funcDone, funcError) {
let req = new XMLHttpRequest();
if (query) {
let params = new URLSearchParams(query);
path = path + "?" + params.toString();
}
req.open(method, path, true);
req.onreadystatechange = function () {
if (req.readyState == XMLHttpRequest.DONE) {
let status = req.status;
if (status === 0 || (status >= 200 && status < 400)) {
if (funcDone)
funcDone(req.responseText, status);
} else {
if (funcError)
funcError(req.responseText, status);
}
}
}
if (body) {
req.setRequestHeader("Content-Type", "application/json");
console.log("SENDING", body)
req.send(JSON.stringify(body));
} else {
req.send();
}
return req;
}