var CounterRefresh = 0
function DtAjax()
{
var dt = new Date();
return 'time=' + dt.getTime().toString()
}
var RqObj
var RqFn
var RqLk
var RqProc = false
var RqFinished = true
var RqConnect = true
function goCmdAjax(fReturn, ajMethod, ajUrl, ajBody, ajHeaders)
{
RqFinished = false;
try {
RqObj = new XMLHttpRequest();
}
catch (e) {
RqObj = null;
return false;
}
RqFn = fReturn
RqLk = ajUrl
ajxUrl = ajUrl
//if (ajxUrl.indexOf('?') != -1) { ajxUrl += "&" } else { ajxUrl += "?" }
//ajxUrl += "View=emb&Con=Ajx"
//http_request = new XMLHttpRequest();
//http_request.overrideMimeType("text/xml"); //Método GET
//http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=iso-8859-1'); //Método POST
// Remove as possibilidades de pegar arquivos do cache
//http_request.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
//http_request.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
//http_request.setRequestHeader("Pragma", "no-cache");
// Função para a resposta
RqObj.onreadystatechange = ReturnCmdAjax
RqObj.onerror = function () {
RqFinished = true;
RqConnect = false;
setTimeout('RqConnect = true', 90 * 1000);
ShowMsg(3, 'Erro de conexão com o Web Service.');
};
// Solicitação
RqObj.open(ajMethod, ajxUrl, true);
//if (ajMethod == 'POST') { RqObj.setRequestHeader('Content-Type', 'application/json'); RqObj.setRequestHeader('Data-Type', 'JSON'); }
if ((ajMethod == 'POST') && (ajHeaders == null))
{ RqObj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); }
if (ajHeaders != null) {
for (aHe of ajHeaders) {
RqObj.setRequestHeader(aHe[0], aHe[1]);
}
}
try {
RqObj.send(ajBody);
}
catch (e) {
RqFinished = true;
ShowMsg(3, 'Erro de comunicação', 'Não foi possível acesso ao servidor web.');
}
//document.body.style.cursor = 'wait';
RqProc = true
if (fReturn != null)
if ((ajBody == null) || ((ajBody != null) && (ajBody != 'silence')))
WaitAjax()
return RqObj;
/*
// 1. Create a new XMLHttpRequest object
let xhr = new XMLHttpRequest();
// 2. Configure it: GET-request for the URL /article/.../load
xhr.open('GET', '/article/xmlhttprequest/example/load');
// 3. Send the request over the network
xhr.send();
// 4. This will be called after the response is received
xhr.onload = function() {
if (xhr.status != 200) { // analyze HTTP status of the response
alert(`Error ${xhr.status}: ${xhr.statusText}`); // e.g. 404: Not Found
} else { // show the result
alert(`Done, got ${xhr.response.length} bytes`); // response is the server
}
};
xhr.onprogress = function(event) {
if (event.lengthComputable) {
alert(`Received ${event.loaded} of ${event.total} bytes`);
} else {
alert(`Received ${event.loaded} bytes`); // no Content-Length
}
};
xhr.onerror = function() {
alert('Request failed');
};
*/
}
function ReturnCmdAjax() {
// Status Atual
switch (RqObj.readyState) {
case 1:
//A carregar
break;
case 2:
//Carregando
break;
case 3:
//Interactivo
break;
case 4:
//Completo
RqProc = false
UnWaitAjax()
//RqFn(RqObj.responseText)
ReturnWs(RqObj.responseText, RqFn)
// Status do Pedido
switch (RqObj.status) {
case 200:
//Tudo OK
//http_request.responseText - devolver a resposta do servidor como uma linha de texto
//http_request.responseXML - devolver a resposta do servidor como um objecto XMLDocument que pode percorrer usando as funções DOM de JavaScript.
//document.body.style.cursor = '';
//RqLk = RqLk.replace('View=emb&', '')
//RqLk = RqLk.replace('Con=Ajx&', '')
//RqLk = RqLk.replace('View=emb', '')
//RqLk = RqLk.replace('Con=Ajx', '')
//if (RqLk.substr(-1,1) == '?') { RqLk = RqLk.replace('?', '') }
//const stateObj = { foo: 'bar' };
//history.replaceState(stateObj, document.title, RqLk);
break;
case 404:
//Página Não Encontrada
//alert('A página solicitada pelo AJAX não foi encontrada')
break;
case 500:
//Erro de processamento no Servidor
//alert('A página solicitada pelo AJAX contém erro de processamento no servidor')
break;
}
break;
}
RqFinished = true;
}
function WaitAjax() {
blackColor = false;
if ((typeof (document.all.cssLinkTag) !== 'undefined')) {
if (document.all.cssLinkTag[0])
if (document.all.cssLinkTag[0].href.indexOf('black') > -1)
blackColor = true;
if (document.all.cssLinkTag[1])
if (document.all.cssLinkTag[1].href.indexOf('black') > -1)
blackColor = true;
}
TxWait = "
"
TxWait += "
"
TxWait += ""
TxWait += " | Processando, por favor aguarde... | ";
TxWait += " "
TxWait += " |
"
TxWait += "
";
//alert(TxJan)
document.body.insertAdjacentHTML('afterBegin', TxWait);
}
function UnWaitAjax() {
if (typeof document.all.WaitAj !== 'undefined') {
if (typeof document.all.WaitAj[0] !== 'undefined') {
for (lcuwa = 0; lcuwa <= 3; lcuwa++) {
if (typeof document.all.WaitAj[lcuwa].parentNode !== 'undefined') {
document.all.WaitAj[lcuwa].parentNode.removeChild(document.all.WaitAj[lcuwa]);
}
}
}
}
if (typeof document.all.WaitAj !== 'undefined') {
if (typeof document.all.WaitAj.parentNode !== 'undefined') {
document.all.WaitAj.parentNode.removeChild(document.all.WaitAj);
}
}
}
async function AJAXSubmit(oFormElement, oResultName) {
var resultElement = oFormElement.elements.namedItem(oResultName);
const formData = new FormData(oFormElement);
var postHeaderAjx = new Headers();
/*--------------not store it anymore
if ((typeof (us) !== 'undefined') && (typeof (pw) !== 'undefined')) {
postHeaderAjx.append('ans-usr', us);
postHeaderAjx.append('ans-pwd', pw);
}--------------not store it anymore
*/
try {
const response = await fetch(oFormElement.action, {
method: 'POST',
headers: postHeaderAjx,
body: formData
});
if (response.ok) {
//alert('Arquivo recebido com sucesso.')
//window.location.href = '/';
RqObj = response;
data = await response.text();
ReturnWs(data, null)
}
if (resultElement != null)
resultElement.value = 'Result: ' + response.status + ' ' +
response.statusText;
} catch (error) {
if (resultElement != null)
resultElement.value = 'Error: ' + error;
else
console.log('Error: ' + error);
}
}
function ReturnWs(content, postFunction) {
var ShowMsgDialog = true;
if (RqObj.getResponseHeader) {
if (RqObj.getResponseHeader('MsgDialog')) {
if (RqObj.getResponseHeader('MsgDialog') == 'none') {
ShowMsgDialog = false;
}
}
}
if (RqObj.status != '') {
RqConnect = true;
if (RqObj.status != 200)
if (ShowMsgDialog)
return ShowMsg(3, 'Erro ao processar sua solicitação.');
}
if (RqObj.status == '') {
if (RqConnect) {
RqConnect = false;
setTimeout('RqConnect = true', 90 * 1000);
return ShowMsg(3, 'Ocorreu algum erro de comunicação com o servidor web.');
}
return;
}
//if ((content == null) || (content == ''))
//return ShowMsg(3, 'Ocorreu algum erro ao retornado o conteúdo do webservice.');
//while (content.indexOf('\\u0022') > -1)
//content = content.replace('\\u0022', "\"")
//mContent = content.replace(/\\u0022/gi, '\\"')
/*
if (RqObj.getResponseHeader) {
if (RqObj.getResponseHeader('Content-Type')) {
if (RqObj.getResponseHeader('Content-Type').indexOf('application/json') == -1) {
if (postFunction) { postFunction(content); } return;
}
}
}
*/
let ls;
var isJson = false;
try {
ls = JSON.parse(content);
isJson = true;
} catch (e) {
isJson = false;
}
if (typeof CheckBtDebug !== 'undefined')
CheckBtDebug();
if (isJson)
if (!CheckRespWs(ls)) {
return false;
}
if (postFunction)
postFunction(isJson ? ls : content);
}
var SaveLastData
function CheckRespWs(js) {
SaveLastData = null
if (js.hasOwnProperty('Debug')) {
if (js['Debug'] != null) {
if (js['Debug'].length > 0) {
if (document.all.btActDebug) {
SaveLastData = js;
if (Get_Cookie('iAdminDebugViewer') == 'yes')
OpenJsonDebugger(js)
else if (js['Code'])
if ((js['Code'] != 1) && (js['Code'] != 4))
OpenJsonDebugger(js)
}
}
}
}
CleanValidate();
if (js == null)
return ShowMsg(2, 'Nenhum registro foi retornado.');
else if (js.length == 0)
return ShowMsg(2, 'Nenhum registro foi encontrado.');
else if ((js.hasOwnProperty('Code')) && (js['Code'] == 4)) {
ProcessValidate(js);
return ShowMsg(4, js['Title'], js['Descr']);
}
else if ((js.hasOwnProperty('Code')) && (!js.hasOwnProperty('Title')) && (js.hasOwnProperty('Descr')))
return ShowMsg(js['Code'], js['Descr']);
else if ((!js.hasOwnProperty('Code')) && (!js.hasOwnProperty('Title')) && (js.hasOwnProperty('Descr')))
return ShowMsg(0, js['Descr']);
else if ((js.hasOwnProperty('Code')) && (js.hasOwnProperty('Title')) && (js.hasOwnProperty('Descr')))
return ShowMsg(js['Code'], js['Title'], js['Descr']);
//if (typeof(js['Code']) !== 'undefined') {
//return ShowMsg(js['Code'], js['Title'], js['Descr']);
//}
/*
if (js['Code'] == 2)
if (js['Descr'])
return ShowMsg(2, js['Title'], js['Descr']);
else
return ShowMsg(2, 'Opsss, algo aconteceu.', js['Title']);
if (js['Code'] == 3)
if (js['Descr'])
return ShowMsg(3, js['Title'], js['Descr']);
else
return ShowMsg(3, 'Opsss, tivemos um problema.', js['Title']);
if (js['Code'] == 4) {
ProcessValidate(js);
return ShowMsg(4, js['Title'], js['Descr']);
}
*/
return true;
}
function isValidJSON(str)
{
try {
JSON.parse(str);
return true;
} catch (e) {
return false;
}
}