const SipeHttp = {}; SipeHttp.newReq = (url, method, data) => { return new Promise(function (resolve, reject) { const xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"); xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status === 200) { let s = xhr.responseText; if (!s) { resolve(null); return; } s = s.trim(); if (!s) { resolve(null); return; } let res; if (s.startsWith('{') && s.endsWith('}')) { res = JSON.parse(s); const erro = res.error || res.erro; if (erro) { reject('Ocorreu um erro ao tentar realizar a operação: ' + erro); return; } } else if (s.startsWith('[') && s.endsWith(']')) { res = JSON.parse(s); } else { res = s; } resolve(res); } else { reject('Erro na requisição: ' + xhr.status); } } }; xhr.open(method, url, true); xhr.setRequestHeader('Content-Type', 'application/json'); if (data) { xhr.send(JSON.stringify(data)); } else { xhr.send(); } }); }; SipeHttp.get = (url) => SipeHttp.newReq(url, 'GET'); SipeHttp.post = (url, data) => SipeHttp.newReq(url, 'POST', data); SipeHttp.toString = (array, path, obj) => { if (!obj) { return ""; } else if (typeof(obj) === 'object') { if (path) { path += "."; } else { path = ""; } for (const a in obj) { SipeHttp.toString(array, path+a, obj[a]); } } else { array.push(path + "=" + obj); } if (array.length) { return "?" + array.join("&"); } else { return ""; } }; SipeHttp.action = (action, metodo, params) => { const url = "/sipe/" + action + "!" + metodo + ".action" + SipeHttp.toString([], "", params); return SipeHttp.get(url); //return SipeHttp.post(url, params); }; SipeHttp.exec = (action, params) => SipeHttp.action(action, "exec", params);