XML to JSON

This commit is contained in:
2023-10-23 13:40:20 +06:00
parent 4ddea79113
commit f3618efc7e
7 changed files with 11177 additions and 264 deletions

View File

@ -102,7 +102,7 @@ class EdtRec
{ {
field.value=value; field.value=value;
}else{ }else{
console.error('Field "'+propName+'" not found!'); log.error('Field "'+propName+'" not found!');
} }
} }
@ -1202,8 +1202,9 @@ class EdtRec
applyReq(req,fn,node,xmldoc,win) applyReq(req,fn,node,xmldoc,win)
{ {
this.hideProgressBar(); this.hideProgressBar();
if (fn==-1) {
let fullText = findFirstNode(node,'#cdata-section').nodeValue; if(node.errorCode>0) {
let fullText = node.errorMessage;
let smallText = ''; let smallText = '';
let pos1=fullText.indexOf('[['); let pos1=fullText.indexOf('[[');
let pos2=fullText.indexOf(']]'); let pos2=fullText.indexOf(']]');
@ -1224,7 +1225,9 @@ class EdtRec
else else
alert2(trt('Alert'), fullText); alert2(trt('Alert'), fullText);
} }
} else return;
}
if (fn==0) { if (fn==0) {
this.eRecNo(node,this.record_id); this.eRecNo(node,this.record_id);
} else } else

78
metadata/dbms/log.js Normal file
View File

@ -0,0 +1,78 @@
// Самодельный логгер, почти аналог: https://thecode.media/winston/
class Log
{
constructor()
{
this.data = [];
this.win = null;
}
show() {
if (this.win != null) this.win.Close();
this.win = new TWin();
this.win.divsh.onclick = null;
this.win.shadow = false;
//this.win.setParent(this.parent.win);
this.win.BuildGUI(10, 10);
this.win.setCaption(trt('Log'));
this.win.setContent('<div id="log_' + this.win.uid + '" style="height:100%;width:100%;"></div>');
this.win.setSize("600px", "260px");
this.win.setCenter();
this.win.hide(false);
this.addLine(true);
}
hide(){
if(this.win!=null) this.win.Close();
this.win=null;
}
addLine(all){
if (this.win == null) return;
let elem = document.getElementById("log_" + this.win.uid);
let i = 0;
if(!all) i = this.data.length-1;
for (;i < this.data.length;i++) {
let div = document.createElement('div');
if(this.data[i].p==1){
div.style.cssText='color: maroon; width:100%;';
}
else if(this.data[i].p==2){
div.style.cssText='color: green; width:100%;';
}
else if(this.data[i].p==3){
div.style.cssText='color: orange; width:100%;';
}
else if(this.data[i].p==4){
div.style.cssText='color: red; width:100%;';
}
div.innerHTML = "["+this.data[i].t+"] "+this.data[i].d;
elem.appendChild(div);
}
}
getTime(){
let data=new Date();
return ('0'+data.getHours()).slice(-2)+":"+('0'+data.getMinutes()).slice(-2)+":"+('0'+data.getSeconds()).slice(-2)+":"+('00'+data.getMilliseconds()).slice(-3);
}
debug(msg){
this.data.push({"p":1,"d":msg,"t": this.getTime()});
this.addLine(false);
}
info(msg){
this.data.push({"p":2,"d":msg,"t": this.getTime()});
this.addLine(false);
}
warn(msg){
this.data.push({"p":3,"d":msg,"t": this.getTime()});
this.addLine(false);
}
error(msg){
this.data.push({"p":4,"d":msg,"t": this.getTime()});
this.addLine(false);
}
}
var log = new Log();
/*log.debug("log.debug");
log.info("log.info");
log.warn("log.warn");
log.error("log.error");*/

View File

@ -18,12 +18,11 @@ class DBMSUser
applyReq(req,fn,node) applyReq(req,fn,node)
{ {
//alert(getXMLNodeSerialisation(node));
this.showShadow(false); this.showShadow(false);
if (fn==-1) if(node.errorCode>0) {
{ alert2(trt('Alert'), node.errorMessage);
alert(findFirstNode(node,'#cdata-section').nodeValue); }
}else
if(fn==7) if(fn==7)
{ {
var nCmd=findFirstNode(node, "cmd"); var nCmd=findFirstNode(node, "cmd");
@ -95,7 +94,7 @@ class DBMSUser
deleteHTML('TWin_CL_'+this.win.uid); //Удаляю кнопку закрыть deleteHTML('TWin_CL_'+this.win.uid); //Удаляю кнопку закрыть
this.win.setCaption(trt('Authorization')); this.win.setCaption(trt('Authorization'));
this.win.setSize("350px","200px"); this.win.setSize("350px","184px");
var str='<div style="width: 100%; height: 100%; padding: 3px; text-align: left;">\n\ var str='<div style="width: 100%; height: 100%; padding: 3px; text-align: left;">\n\
<table cellpadding="0" cellspacing="0" style="width: 100%; height: 100%;">\n\ <table cellpadding="0" cellspacing="0" style="width: 100%; height: 100%;">\n\

View File

@ -38,13 +38,16 @@
return substr($path,0,$position); return substr($path,0,$position);
} }
function sendError($e) function sendError($code, $error)
{ {
header('Content-type: text/xml'); $obj = new StdClass();
header("Cache-Control: no-cache, must-revalidate"); $obj->errorCode=$code;
echo '<?xml version="1.0" encoding="utf-8"?><metadata fn="-1"><![CDATA['.$e.']]></metadata>'; $obj->errorMessage=$error;
Exit(); header('Content-Type: application/json');
} header("Cache-Control: no-cache, must-revalidate");
echo json_encode($obj);
exit();
}
function getSQLValue($t,$v) function getSQLValue($t,$v)
{ {
@ -174,13 +177,13 @@
} }
if($xmls!='') if($xmls!='')
{ {
//sendError("Metadata node \"".$name."\" not find in database!"); //sendError(1,"Metadata node \"".$name."\" not find in database!");
$objXMLDocument = new DOMDocument(); $objXMLDocument = new DOMDocument();
try try
{ {
$objXMLDocument->loadXML($xmls); $objXMLDocument->loadXML($xmls);
} catch (Exception $e) } catch (Exception $e)
{ sendError($e->getMessage()); { sendError(1,$e->getMessage());
} }
$currNode=findNodeOnAttribute($objXMLDocument->documentElement, "type","n",$name); $currNode=findNodeOnAttribute($objXMLDocument->documentElement, "type","n",$name);
return $currNode; return $currNode;
@ -191,7 +194,7 @@
function special_handler($exception) function special_handler($exception)
{ {
sendError($exception->getMessage()); sendError(1,$exception->getMessage());
} }
set_exception_handler('special_handler'); //чтоб не пойманные исключения посылались в виде XML set_exception_handler('special_handler'); //чтоб не пойманные исключения посылались в виде XML
@ -217,7 +220,7 @@
} }
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $e) } catch (Exception $e)
{ sendError('Connect error '.$_SERVER['HTTP_HOST'].': "'.$e->getMessage().'"!'); { sendError(1,'Connect error '.$_SERVER['HTTP_HOST'].': "'.$e->getMessage().'"!');
} }
//Пытаемся автоматически залогинется по GUID из COOKIE (TODO авторизация должна быть в отдельном файле! Смотри директорию password ) //Пытаемся автоматически залогинется по GUID из COOKIE (TODO авторизация должна быть в отдельном файле! Смотри директорию password )
@ -243,7 +246,7 @@
$doc->loadXML($HTTP_INPUT); $doc->loadXML($HTTP_INPUT);
} catch (Exception $e) } catch (Exception $e)
{ {
sendError($e->getMessage()); sendError(1,$e->getMessage());
} }
$reqNode = $doc->documentElement; $reqNode = $doc->documentElement;
@ -282,7 +285,7 @@
$allow_upd=false; $allow_upd=false;
$allow_del=false; $allow_del=false;
$sql_query='select '.$Schema.'p_getaccess(:user_id1,:action_insert) as ins,'.$Schema.'p_getaccess(:user_id2,:action_update) as upd,'.$Schema.'p_getaccess(:user_id3,:action_delete) as del;'; $sql_query='select '.$Schema.'p_getaccess(:user_id1,:action_insert) as ins,'.$Schema.'p_getaccess(:user_id2,:action_update) as upd,'.$Schema.'p_getaccess(:user_id3,:action_delete) as del;';
$stmt = $db->prepare($sql); $stmt = $db->prepare($sql_query);
$stmt->bindValue(':user_id1', $_SESSION['USER_ID'], PDO::PARAM_INT); //getSQLValue(gettype($_SESSION['USER_ID']),$_SESSION['USER_ID']) $stmt->bindValue(':user_id1', $_SESSION['USER_ID'], PDO::PARAM_INT); //getSQLValue(gettype($_SESSION['USER_ID']),$_SESSION['USER_ID'])
$stmt->bindValue(':user_id2', $_SESSION['USER_ID'], PDO::PARAM_INT); //getSQLValue(gettype($_SESSION['USER_ID']),$_SESSION['USER_ID']) $stmt->bindValue(':user_id2', $_SESSION['USER_ID'], PDO::PARAM_INT); //getSQLValue(gettype($_SESSION['USER_ID']),$_SESSION['USER_ID'])
$stmt->bindValue(':user_id3', $_SESSION['USER_ID'], PDO::PARAM_INT); //getSQLValue(gettype($_SESSION['USER_ID']),$_SESSION['USER_ID']) $stmt->bindValue(':user_id3', $_SESSION['USER_ID'], PDO::PARAM_INT); //getSQLValue(gettype($_SESSION['USER_ID']),$_SESSION['USER_ID'])
@ -324,7 +327,7 @@
Exit(); Exit();
}else }else
{ {
sendError('Не найден запрошенный узел: "'.$typename.'"!'); sendError(1,'Не найден запрошенный узел: "'.$typename.'"!');
} }
}else }else
if ($fn==1) //вставка записи (результат id записи) if ($fn==1) //вставка записи (результат id записи)
@ -371,7 +374,7 @@
$path= $_SERVER['DOCUMENT_ROOT'].'/'.findFirstNodeOnAttribute($currNode,"prop","n",$nodePropData->getAttribute("n"))->getAttribute("path"); $path= $_SERVER['DOCUMENT_ROOT'].'/'.findFirstNodeOnAttribute($currNode,"prop","n",$nodePropData->getAttribute("n"))->getAttribute("path");
@mkdir($path); //Создаём папку если её нет @mkdir($path); //Создаём папку если её нет
if(!rename($dir.$flnm, $path.$flnm)) if(!rename($dir.$flnm, $path.$flnm))
sendError('Can\'t rename to "'.$path.$v.'"!'); sendError(1,'Can\'t rename to "'.$path.$v.'"!');
} }
}else }else
{ $v=getSQLValue($vt, getCdataValue($nodePropData)); { $v=getSQLValue($vt, getCdataValue($nodePropData));
@ -383,7 +386,7 @@
$sql_query=str_replace('${_user_id}',getSQLValue(gettype($_SESSION['USER_ID']),$_SESSION['USER_ID']),$sql_query); //Потому что PostgreSQL не может хранить id пользователя привязаного к сесии $sql_query=str_replace('${_user_id}',getSQLValue(gettype($_SESSION['USER_ID']),$_SESSION['USER_ID']),$sql_query); //Потому что PostgreSQL не может хранить id пользователя привязаного к сесии
$stmt = $db->prepare($sql_query); $stmt = $db->prepare($sql_query);
if($stmt === false) sendError('Error preparing Statement'); if($stmt === false) sendError(1,'Error preparing Statement');
//присваеваем параметрам значения (В записи может быть только 1 двоичное поля см bindParam или сделать несколько переменных) //присваеваем параметрам значения (В записи может быть только 1 двоичное поля см bindParam или сделать несколько переменных)
$nodePropData=$nodeProp->firstChild; $nodePropData=$nodeProp->firstChild;
@ -406,12 +409,15 @@
} }
$nodePropData=$nodePropData->nextSibling; $nodePropData=$nodePropData->nextSibling;
} }
try try
{ {
$res = $stmt->execute(); $res = $stmt->execute();
} catch (Exception $e) } catch (Exception $e)
{ sendError($e->getMessage()); {
if(str_contains($e->getMessage(), ']]'))
sendError(1, $e->getMessage());
else
sendError(1, '[['.trt("SQL_query_error").']]'.$e->getMessage());
} }
$result = $stmt->fetch(PDO::FETCH_NUM); $result = $stmt->fetch(PDO::FETCH_NUM);
if($result[0]=='') if($result[0]=='')
@ -419,7 +425,7 @@
if(strpos($db_connection, 'sqlite')!==false) { if(strpos($db_connection, 'sqlite')!==false) {
$result[0] = $db->lastInsertId(); //Для SQLite $result[0] = $db->lastInsertId(); //Для SQLite
}else{ }else{
sendError(trt('Failed_to_insert_record').'!'); sendError(1,trt('Failed_to_insert_record').'!');
} }
} }
@ -430,7 +436,7 @@
Exit(); Exit();
}else }else
{ {
sendError('Не найден запрошенный узел: "'.$typename.'"!'); sendError(1,'Не найден запрошенный узел: "'.$typename.'"!');
} }
}else }else
if ($fn==2) //редактирование (результат id записи) if ($fn==2) //редактирование (результат id записи)
@ -479,8 +485,8 @@
{ {
$path= $_SERVER['DOCUMENT_ROOT'].'/'.findFirstNodeOnAttribute($currNode,"prop","n",$nodePropData->getAttribute("n"))->getAttribute("path"); $path= $_SERVER['DOCUMENT_ROOT'].'/'.findFirstNodeOnAttribute($currNode,"prop","n",$nodePropData->getAttribute("n"))->getAttribute("path");
@mkdir($path);//Создаём папку если её нет @mkdir($path);//Создаём папку если её нет
if(!rename($dir.$flnm, $path.$flnm)) if(!rename($dir.$flnm, $path.$flnm))
sendError('Can\'t rename to "'.$path.$v.'"!'); sendError(1,'Can\'t rename to "'.$path.$v.'"!');
} }
}else }else
{ {
@ -493,9 +499,9 @@
$sql_query=str_replace('${_user_id}',getSQLValue(gettype($_SESSION['USER_ID']),$_SESSION['USER_ID']),$sql_query); //Потому что PostgreSQL не может хранить id пользователя привязаного к сесии $sql_query=str_replace('${_user_id}',getSQLValue(gettype($_SESSION['USER_ID']),$_SESSION['USER_ID']),$sql_query); //Потому что PostgreSQL не может хранить id пользователя привязаного к сесии
$sql_query=str_replace('${'.$currNode->getAttribute("ObjectID").'}',getSQLValue(gettype($obj_id),$obj_id),$sql_query); //Так как пока идентификатор базы отдельно передаётся $sql_query=str_replace('${'.$currNode->getAttribute("ObjectID").'}',getSQLValue(gettype($obj_id),$obj_id),$sql_query); //Так как пока идентификатор базы отдельно передаётся
//sendError($sql_query); //sendError(1,$sql_query);
$stmt = $db->prepare($sql_query); $stmt = $db->prepare($sql_query);
if($stmt === false) sendError('Error preparing Statement'); if($stmt === false) sendError(1,'Error preparing Statement');
//Присваеваем параметру двоичную информацию (Внимание! Только 1 параметр может быть в 1 записи (почему?)) //Присваеваем параметру двоичную информацию (Внимание! Только 1 параметр может быть в 1 записи (почему?))
$pos_v = 0; $pos_v = 0;
@ -528,7 +534,7 @@
try try
{ $res = $stmt->execute(); { $res = $stmt->execute();
} catch (Exception $e) } catch (Exception $e)
{ sendError($e->getMessage()."\n".$sql_query); { sendError(1,$e->getMessage()."\n".$sql_query);
} }
$result = $stmt->fetch(PDO::FETCH_NUM); //$obj_id $result = $stmt->fetch(PDO::FETCH_NUM); //$obj_id
if($result[0]==''){ $result[0]=$obj_id; } if($result[0]==''){ $result[0]=$obj_id; }
@ -539,7 +545,7 @@
Exit(); Exit();
}else }else
{ {
sendError('Не найден запрошенный узел: "'.$typename.'"!'); sendError(1,'Не найден запрошенный узел: "'.$typename.'"!');
} }
}else }else
if ($fn==3) //удаление (результат id записи) if ($fn==3) //удаление (результат id записи)
@ -563,7 +569,7 @@
try try
{ $res = $db->query($sql_query); { $res = $db->query($sql_query);
}catch (Exception $e) }catch (Exception $e)
{ sendError($e->getMessage()); { sendError(1,$e->getMessage());
} }
//записываем id удалённой записи для удаления без перезагрузки страницы через javascript //записываем id удалённой записи для удаления без перезагрузки страницы через javascript
$xmlstring=""; $xmlstring="";
@ -577,7 +583,7 @@
Exit(); Exit();
}else }else
{ {
sendError('Не найден запрошенный узел: "'.$typename.'"!'); sendError(1,'Не найден запрошенный узел: "'.$typename.'"!');
} }
}else }else
if ($fn==4 || $fn==11) //взять данные из базы по переданным значениям фильтра ($fn==11 для обновления записи у клиента после вставки или редактировании) if ($fn==4 || $fn==11) //взять данные из базы по переданным значениям фильтра ($fn==11 для обновления записи у клиента после вставки или редактировании)
@ -622,12 +628,12 @@
$sql_query=str_replace('${_order}',findNodeOnAttribute(findFirstNode($currNode,'objects-list'), "column","n",$objListR->getAttribute("order"))->getAttribute("order"),$sql_query); $sql_query=str_replace('${_order}',findNodeOnAttribute(findFirstNode($currNode,'objects-list'), "column","n",$objListR->getAttribute("order"))->getAttribute("order"),$sql_query);
}else $sql_query=str_replace('${_order}','1',$sql_query); }else $sql_query=str_replace('${_order}','1',$sql_query);
//sendError($sql_query); //sendError(1,$sql_query);
//Выполняем запрос //Выполняем запрос
try try
{ $res = $db->query($sql_query); { $res = $db->query($sql_query);
} catch (Exception $e) } catch (Exception $e)
{ sendError($e->getMessage().' '.$sql_query); { sendError(1,$e->getMessage().' '.$sql_query);
} }
//Формируем ответ //Формируем ответ
$pagecount=ceil($res->rowCount()/$rowspagecount); //Кол-во страниц $pagecount=ceil($res->rowCount()/$rowspagecount); //Кол-во страниц
@ -663,6 +669,7 @@
} }
//перебираем RS и строим XML только из тех столбцов которые записанны в секци objects-list поля column в не зависимости от их видимости //перебираем RS и строим XML только из тех столбцов которые записанны в секци objects-list поля column в не зависимости от их видимости
/*
$xmlstring=''; $xmlstring='';
$xmlstring.='<?xml version="1.0" encoding="utf-8"?>'."\n"; $xmlstring.='<?xml version="1.0" encoding="utf-8"?>'."\n";
$xmlstring.='<metadata fn="'.$fn.'"><type n="'.$typename.'" pc="'.$pagecount.'" pp="'.$pagepos.'">'."\n"; $xmlstring.='<metadata fn="'.$fn.'"><type n="'.$typename.'" pc="'.$pagecount.'" pp="'.$pagepos.'">'."\n";
@ -708,7 +715,7 @@
$xmlstring.='<![CDATA['.$row[$field].']]>'; $xmlstring.='<![CDATA['.$row[$field].']]>';
}else }else
{ {
sendError("Column \"".$nextnode->getAttribute("n")."\" not exists in \"$typename\" for select!"); sendError(1,"Column \"".$nextnode->getAttribute("n")."\" not exists in \"$typename\" for select!");
} }
} }
$nextnode = $nextnode->nextSibling; $nextnode = $nextnode->nextSibling;
@ -717,15 +724,82 @@
} }
$res->closeCursor(); $res->closeCursor();
$xmlstring.='</type></metadata>'."\n"; $xmlstring.='</type></metadata>'."\n";
//sendError('pos1='.$xmlstring);
header('Content-type: text/xml'); header('Content-type: text/xml');
echo $xmlstring; echo $xmlstring;
*/
$obj = new StdClass();
$obj->errorCode=0;
$obj->errorMessage = '';
$obj->fn=$fn;
$obj->n=$typename;
$obj->pc=$pagecount;
$obj->pp=$pagepos;
//Перечисляю название выбираемых столбцов через запятую (почему в JAVA версии этого куска кода нет?)
$obj->objects_list=[];
$nextnode=findNode($currNode,'objects-list')->firstChild;
while ($nextnode)
{
if ($nextnode->nodeName=='column')
{
array_push($obj->objects_list,$nextnode->getAttribute("n"));
}
$nextnode = $nextnode->nextSibling;
}
$obj->data=[];
$node=findFirstNode($reqNode,'objects-list');
$pos=-1;
while ($row = $res->fetch(PDO::FETCH_ASSOC))// $row - ассоциативный массив значений, ключи - названия столбцов
{
$pos++;
if (($pagepos!=-1)&&(($pos<($pagepos*$rowspagecount))||($pos>=$pagepos*$rowspagecount+$rowspagecount))) { continue; }
array_push($obj->data,new StdClass());
//разрешать или запрещять редактировать запись надо проверять в хранимке а также запрещять либо разрешать редактировать колонку
//для каждой записи формируеться строка настроек со значениями что нужно запретить в таком виде "iuds"
$access=''; //u = enable update field, d = enable delete field
if(!array_key_exists("_u",$row)) { $access.="u"; } else { $access.=$row["_u"]; }
if(!array_key_exists("_d",$row)) { $access.="d"; } else { $access.=$row["_d"]; }
if(array_key_exists($currNode->getAttribute("ObjectID"),$row)) {
end($obj->data)->id=$row[$currNode->getAttribute("ObjectID")];
end($obj->data)->a=$access;
}else {
end($obj->data)->id="";
end($obj->data)->a=$access;
}
end($obj->data)->row=[];
$nextnode=findNode($currNode,'objects-list')->firstChild;
while ($nextnode)
{
if ($nextnode->nodeName=='column')
{
if(array_key_exists($nextnode->getAttribute("n"),$row))
{
$field = $nextnode->getAttribute("n");
array_push(end($obj->data)->row,$row[$field]);
}else
{
sendError(1,"Column \"".$nextnode->getAttribute("n")."\" not exists in \"$typename\" for select!");
}
}
$nextnode = $nextnode->nextSibling;
}
}
$res->closeCursor();
header('Content-Type: application/json; charset=utf-8');
header("Cache-Control: no-cache, must-revalidate");
echo json_encode($obj);
exit;
}else }else
{ {
sendError("Не найден запрошеный узел!"); sendError(1,"Не найден запрошеный узел!");
} }
}else }else
if ($fn==5) //вернуть клиенту данные по id для редактирования одной записи if ($fn==5) //вернуть клиенту данные по id для редактирования одной записи
@ -752,16 +826,16 @@
$sql_query=str_replace('${_user_id}',getSQLValue(gettype($_SESSION['USER_ID']),$_SESSION['USER_ID']),$sql_query); $sql_query=str_replace('${_user_id}',getSQLValue(gettype($_SESSION['USER_ID']),$_SESSION['USER_ID']),$sql_query);
} }
} }
//sendError($sql_query); //sendError(1,$sql_query);
try try
{ {
$res = $db->query($sql_query); $res = $db->query($sql_query);
} catch (Exception $e) } catch (Exception $e)
{ sendError($e->getMessage()); { sendError(1,$e->getMessage());
} }
if(strpos($db_connection, 'sqlite')===false) //Для SQLite не работает rowCount() if(strpos($db_connection, 'sqlite')===false) //Для SQLite не работает rowCount()
{ {
if($res->rowCount()!=1) sendError("Количество записей не равно одному!"); if($res->rowCount()!=1) sendError(1,"Количество записей не равно одному!");
} }
$xmls=''; $xmls='';
@ -772,7 +846,7 @@
} }
if($xmls=='') if($xmls=='')
{ {
sendError("Metadata node \"".$name."\" is empty!"); sendError(1,"Metadata node \"".$name."\" is empty!");
} }
//загружаем мета данные и смотрим какие поля должны передать клиенту //загружаем мета данные и смотрим какие поля должны передать клиенту
@ -781,7 +855,7 @@
{ {
$mdoc->loadXML($xmls); $mdoc->loadXML($xmls);
} catch (Exception $e) } catch (Exception $e)
{ sendError($e->getMessage()); { sendError(1,$e->getMessage());
} }
//находим нужный узел //находим нужный узел
$node=findNodeOnAttribute($mdoc->documentElement, "type","n",$typename); $node=findNodeOnAttribute($mdoc->documentElement, "type","n",$typename);
@ -816,7 +890,7 @@
if(array_key_exists($nextnode->getAttribute("cd"), $row)) { if(array_key_exists($nextnode->getAttribute("cd"), $row)) {
$xmlstring .= '<prop n="' . $nextnode->getAttribute("n") . '"><![CDATA[' . $row[$nextnode->getAttribute("cd")] . ']]></prop>' . "\n"; $xmlstring .= '<prop n="' . $nextnode->getAttribute("n") . '"><![CDATA[' . $row[$nextnode->getAttribute("cd")] . ']]></prop>' . "\n";
}else{ }else{
sendError('Поле "'.$nextnode->getAttribute("cd").'" не найдено в результирующем наборе!'); sendError(1,'Поле "'.$nextnode->getAttribute("cd").'" не найдено в результирующем наборе!');
} }
} }
else { else {
@ -824,10 +898,10 @@
} }
}else }else
{ {
sendError('Поле "'.$nextnode->getAttribute("n").'" не найдено в результирующем наборе!'); sendError(1,'Поле "'.$nextnode->getAttribute("n").'" не найдено в результирующем наборе!');
} }
} catch (Exception $e) { sendError($e->getMessage()); } } catch (Exception $e) { sendError(1,$e->getMessage()); }
} }
$nextnode = $nextnode->nextSibling; $nextnode = $nextnode->nextSibling;
} }
@ -853,7 +927,7 @@
$currNode=getMetadataNode($typename); $currNode=getMetadataNode($typename);
if($currNode==null) sendError("Not find \"".$typename."\"!"); if($currNode==null) sendError(1,"Not find \"".$typename."\"!");
$objXMLDocument=$currNode->ownerDocument; $objXMLDocument=$currNode->ownerDocument;
$objListR = findFirstNode($tNodeR,'objects-list'); //Из запроса $objListR = findFirstNode($tNodeR,'objects-list'); //Из запроса
@ -884,7 +958,7 @@
try try
{ $res = $db->query($sql_query); { $res = $db->query($sql_query);
} catch (Exception $e) } catch (Exception $e)
{ sendError($e->getMessage()); { sendError(1,$e->getMessage());
} }
//выбираем данные из базы и отправляем клиенту //выбираем данные из базы и отправляем клиенту
@ -903,7 +977,7 @@
$val.=$row[$columns[$i]]; $val.=$row[$columns[$i]];
}else }else
{ {
sendError("Column \"$columns[$i]\" not exists in \"$typename\" for select to drop down list!"); sendError(1,"Column \"$columns[$i]\" not exists in \"$typename\" for select to drop down list!");
} }
} }
$xmlstring.='<![CDATA['.$val.']]>'; $xmlstring.='<![CDATA['.$val.']]>';
@ -961,7 +1035,7 @@
$html .= '</body></html>'; $html .= '</body></html>';
//mail($login,'rigor.kz','Not implement',"Content-type: text/html; charset=utf-8\r\nFrom: rigor Site <info@rigor.kz>"); //mail($login,'rigor.kz','Not implement',"Content-type: text/html; charset=utf-8\r\nFrom: rigor Site <info@rigor.kz>");
if (!mail($login, 'Password for monitoring', $html, "Content-type: text/html; charset=utf-8\r\nFrom: Transit Site <no-reply@istt.kz>")) { if (!mail($login, 'Password for monitoring', $html, "Content-type: text/html; charset=utf-8\r\nFrom: Transit Site <no-reply@istt.kz>")) {
sendError("Failed to send mail to: " . $row["email"]); sendError(1,"Failed to send mail to: " . $row["email"]);
} }
} }
} }
@ -987,7 +1061,7 @@
try try
{ $db->exec($sql); { $db->exec($sql);
} catch (Exception $e) } catch (Exception $e)
{ sendError($e->getMessage()); { sendError(1,$e->getMessage());
} }
unset($_SESSION['USER_ID']); unset($_SESSION['USER_ID']);
@ -1080,7 +1154,7 @@ if ($code!=$_POST['code']) return new AuthError('invalid code');
echo $xs; echo $xs;
exit(); exit();
}else{ }else{
sendError('Command "'.$cmd.'" not find!'); sendError(1,'Command "'.$cmd.'" not find!');
} }
}else }else
@ -1175,9 +1249,9 @@ if ($code!=$_POST['code']) return new AuthError('invalid code');
try try
{ $res = $db->query($sql_query); { $res = $db->query($sql_query);
} catch (Exception $e) } catch (Exception $e)
{ sendError($e->getMessage()); { sendError(1,$e->getMessage());
} }
if($res->rowCount()!=1) sendError(trt('The number of records is not equal to one!').' '.$sql_query); if($res->rowCount()!=1) sendError(1,trt('The number of records is not equal to one!').' '.$sql_query);
$columns=explode(",",$nextnode->getAttribute('FieldCaption')); $columns=explode(",",$nextnode->getAttribute('FieldCaption'));
@ -1227,7 +1301,7 @@ if ($code!=$_POST['code']) return new AuthError('invalid code');
try try
{ $res = $db->query($sql_query); { $res = $db->query($sql_query);
} catch (Exception $e) } catch (Exception $e)
{ sendError($e->getMessage().$sql_query); { sendError(1,$e->getMessage().$sql_query);
} }
//Сохраняем результсет в файл в виде HTML с расширением XLS //Сохраняем результсет в файл в виде HTML с расширением XLS
@ -1315,7 +1389,7 @@ if ($code!=$_POST['code']) return new AuthError('invalid code');
//deleteTempFiles($dir); //deleteTempFiles($dir);
}else }else
{ {
sendError(trt('Not found the requested node:').' "'.$typename.'"!'); sendError(1,trt('Not found the requested node:').' "'.$typename.'"!');
} }
}else }else
@ -1379,7 +1453,7 @@ if ($code!=$_POST['code']) return new AuthError('invalid code');
} }
if($xmls=='') if($xmls=='')
{ {
sendError("Metadata node \"".$name."\" is empty!"); sendError(1,"Metadata node \"".$name."\" is empty!");
} }
//Ищем поле в метаданных //Ищем поле в метаданных
@ -1450,7 +1524,7 @@ if ($code!=$_POST['code']) return new AuthError('invalid code');
} }
}else }else
{ {
sendError("Неизвестная функция \"$fn\"!"); sendError(1,"Неизвестная функция \"$fn\"!");
} }

View File

@ -1,4 +1,4 @@
//Copyright (C) 2008 Ivanov I.M. ivanov.i@istt.kz //Copyright (C) 2008 Igor
//For find non english chars: [^\x00-\x7F]+ //For find non english chars: [^\x00-\x7F]+
function callWindow(uid,id,i) function callWindow(uid,id,i)
@ -49,18 +49,14 @@ class SRec
applyReq(req,fn,node,xmldoc) applyReq(req,fn,node,xmldoc)
{ {
//alert2(trt('Alert'),getXMLNodeSerialisation(node));
this.hideProgressBar(); this.hideProgressBar();
this.xmldoc=node.ownerDocument; //xmldoc; if(node.errorCode>0) {
if (fn==-1) //Information alert let fullText = node.errorMessage;
{
let fullText = findFirstNode(node,'#cdata-section').nodeValue;
let smallText = ''; let smallText = '';
let pos1=fullText.indexOf('[['); let pos1=fullText.indexOf('[[');
let pos2=fullText.indexOf(']]'); let pos2=fullText.indexOf(']]');
if(pos1>=0 && pos2>=0 && pos1<pos2) smallText=fullText.substring(pos1+2, pos2); if(pos1>=0 && pos2>=0 && pos1<pos2) smallText=fullText.substring(pos1+2, pos2);
if(fullText.indexOf("id456[[")>=0){ //Если есть идентификатор того что это перезапись if(fullText.indexOf("id456[[")>=0){ //Если есть идентификатор того что это перезапись
let okFunc=()=>{ let okFunc=()=>{
this.setValue('seq',0); this.setValue('seq',0);
@ -76,7 +72,11 @@ class SRec
else else
alert2(trt('Alert'), fullText); alert2(trt('Alert'), fullText);
} }
}else return;
}
this.xmldoc=node.ownerDocument; //xmldoc;
if (fn==0) if (fn==0)
{ {
//alert2(trt('Alert'),getXMLNodeSerialisation(node)); //alert2(trt('Alert'),getXMLNodeSerialisation(node));
@ -1165,15 +1165,15 @@ class SRec
} }
//Function to insert data into a table. //Function to insert data into a table.
//node - A node with data. //node - A JSON object with data.
//clear - Whether to clear all entries. //clear - Whether to clear all entries.
insertRows(node,clear) insertRows(node,clear)
{ {
let theTable = document.getElementById('thetable'+this.uid); //Data table let theTable = document.getElementById('thetable'+this.uid); //Data table
let nodeType=findFirstNode(node, "type"); //let nodeType=findFirstNode(node, "type");
let pagecount=nodeType.getAttribute("pc"); //total pages let pagecount=node.pc; //total pages
if((nodeType.getAttribute("pp")!=null)&&(nodeType.getAttribute("pp")!=-1)) this.pagepos=nodeType.getAttribute("pp"); this.pagepos=node.pp;
if(clear || this.f_nodeData==null) if(clear || this.f_nodeData==null)
{ this.f_nodeData=node; { this.f_nodeData=node;
@ -1206,6 +1206,10 @@ class SRec
let newCell = newRow.insertCell(-1); let newCell = newRow.insertCell(-1);
newCell.style.backgroundColor = bgColor; newCell.style.backgroundColor = bgColor;
newCell.style.cursor="pointer"; newCell.style.cursor="pointer";
if (this.pagepos==i) {
newCell.style.fontWeight = "bold";
newCell.style.fontSize = "large";
}
newCell.appendChild(document.createTextNode(i+1)); newCell.appendChild(document.createTextNode(i+1));
//Upon clicking, a filter with old values is used only with a different page number. //Upon clicking, a filter with old values is used only with a different page number.
newCell.onclick=function(obj,page){ newCell.onclick=function(obj,page){
@ -1227,123 +1231,115 @@ class SRec
} }
}else }else
{ {
let tmpNR=findFirstNode(this.f_nodeData, "type"); for(let i=0;i<node.data.length;i++){
let nodeRecord = nodeType.firstChild; Object.assign(this.f_nodeData.data, node.data[i])
while (nodeRecord != null)
{
if(nodeRecord.nodeName=="record")
{
tmpNR.appendChild(nodeRecord.cloneNode(true) );
}
nodeRecord = nodeRecord.nextSibling;
} }
} }
//Add new entries //Add new entries
let nColor=findNumNodeOnAttribute(findNodeOnPath(this.nodeMetadata,"type/objects-list"),"column","n","color"); let nColor=findNumNodeOnAttribute(findNodeOnPath(this.nodeMetadata,"type/objects-list"),"column","n","color");
let TypeName = nodeType.getAttribute("n"); let TypeName = node.n;
let i=0; //The position should be received from the server. let i=0; //The position should be received from the server.
let nodeRecord = nodeType.firstChild; for(let i=0;i<node.data.length;i++){
while (nodeRecord != null)
{ let bgColor='';
if(nodeRecord.nodeName=="record") if (i%2==0) bgColor='var(--row-color-1)'; else bgColor='var(--row-color-2)';
//if(nColor>=0) //Color from Result
//{
// let bgColorT=findNodeOnNum(nodeRecord,"#cdata-section",nColor).nodeValue;
// if(bgColorT!="") bgColor=bgColorT;
//}
let id=node.data[i].id;
//add rows to an existing record table
let tr = document.createElement('tr');
tr.onmouseover=function(){ this.style.backgroundColor="var(--btn-color2)"; };
tr.onmouseout=function(val1,val2){return function(){val1.style.backgroundColor=val2;}}(tr,bgColor);
tr.setAttribute("id",id+'_'+this.uid);
tr.style.backgroundColor=bgColor;
//sequential record number
let td = document.createElement('td');
td.appendChild( document.createTextNode( i+1+100*this.pagepos ) );
tr.appendChild(td);
//CheckBuck to delete records
td = document.createElement('td');
td.style.cssText="text-align: center;";
if(!(this.f_pD!="1" || node.data[i].a.indexOf("d")==-1))
{ {
let bgColor=''; let checkbox = document.createElement('input');
let i=theTable.rows.length; //number of rows in the table checkbox.classList.add('DBMS');
if (i%2==0) bgColor='var(--row-color-1)'; else bgColor='var(--row-color-2)'; this.masChBox.push(checkbox);
//checkbox.disabled=true;
if(nColor>=0) //Color from Result checkbox.setAttribute("type","checkbox");
{ checkbox.setAttribute("value",id);
let bgColorT=findNodeOnNum(nodeRecord,"#cdata-section",nColor).nodeValue; checkbox.style.cssText="font: normal normal normal 11px normal Arial;";
if(bgColorT!="") bgColor=bgColorT; td.appendChild( checkbox );
}
let id=nodeRecord.getAttribute("id");
//add rows to an existing record table
let tr = document.createElement('tr');
tr.onmouseover=function(){ this.style.backgroundColor="var(--btn-color2)"; };
tr.onmouseout=function(val1,val2){return function(){val1.style.backgroundColor=val2;}}(tr,bgColor);
tr.setAttribute("id",id+'_'+this.uid);
tr.style.backgroundColor=bgColor;
//sequential record number
let td = document.createElement('td');
td.appendChild( document.createTextNode( i+100*this.pagepos ) );
tr.appendChild(td);
//CheckBuck to delete records
td = document.createElement('td');
td.style.cssText="text-align: center;";
if(!(this.f_pD!="1" || nodeRecord.getAttribute("a").indexOf("d")==-1))
{
let checkbox = document.createElement('input');
checkbox.classList.add('DBMS');
this.masChBox.push(checkbox);
//checkbox.disabled=true;
checkbox.setAttribute("type","checkbox");
checkbox.setAttribute("value",id);
checkbox.style.cssText="font: normal normal normal 11px normal Arial;";
td.appendChild( checkbox );
}
tr.appendChild(td);
//for each column we make a column
let colN=0; //column number
let cdataNode = nodeRecord.firstChild;
while (cdataNode!=null)
{
if(cdataNode.nodeName=="#cdata-section")
{
if(this.masVis[colN])
{
td = document.createElement('td');
if((this.f_pU=="1")||(this.f_State=="1")){
td.style.cssText="cursor: pointer;";
}
let textNode=document.createTextNode(cdataNode.nodeValue);
td.setAttribute("id",id+this.masCL[colN].getAttribute("n")); //so that you can identify each record when you update
td.appendChild(textNode);
//if in the metadata for this column there is a reference object then add a link
if (this.masCT[colN]!=null)
{
//Opening a new window in the filter is passed to the current values of the row
td.style.cssText="cursor: pointer; background-color: var(--btn-color); font-weight: bold;";
td.onmouseover=function(){
this.style.backgroundColor="var(--btn-color2)";
};
td.onmouseout=function(){
this.style.backgroundColor="var(--btn-color)";
};
//when you click on a cell, the sent filter is prefilled with variables in accordance with the id of the pressed line
//in the function we pass the cell id and the column number
td.onclick=function(obj,val1,val2){
return function(){
obj.callWindow(val1,val2);
}
}(this,id,colN);
}else
{
if((this.f_pU=="1" && nodeRecord.getAttribute("a").indexOf("u")!=-1)||(this.f_State=="1"))
{
td.onclick=function(thiz,val1,val2){
return function(){thiz.updateRecord(val1);};
}(this,id);
}else
{
td.style.cssText="cursor: default;";
}
}
tr.appendChild(td);
}
colN++;
}
cdataNode = cdataNode.nextSibling;
}
theTable.tBodies[0].appendChild(tr);
} }
nodeRecord = nodeRecord.nextSibling; tr.appendChild(td);
//for each column we make a column
let colN=0; //column number
//let cdataNode = nodeRecord.firstChild;
//while (cdataNode!=null)
//this.access[obj.data[i].row[0]]=obj.data[i].row[1];
for(let j=0;j<node.data[i].row.length;j++)
{
if(this.masVis[colN])
{
td = document.createElement('td');
if((this.f_pU=="1")||(this.f_State=="1")){
td.style.cssText="cursor: pointer;";
}
let textNode;
if(node.data[i].row[j]!=null) textNode=document.createTextNode(node.data[i].row[j]);
else textNode=document.createTextNode("");
//td.setAttribute("id",id+this.masCL[colN].getAttribute("n")); //so that you can identify each record when you update
td.setAttribute("id",id+this.masCL[colN].n); //so that you can identify each record when you update
td.appendChild(textNode);
//if in the metadata for this column there is a reference object then add a link
if (this.masCT[colN]!=null)
{
//Opening a new window in the filter is passed to the current values of the row
td.style.cssText="cursor: pointer; background-color: var(--btn-color); font-weight: bold;";
td.onmouseover=function(){
this.style.backgroundColor="var(--btn-color2)";
};
td.onmouseout=function(){
this.style.backgroundColor="var(--btn-color)";
};
//when you click on a cell, the sent filter is prefilled with variables in accordance with the id of the pressed line
//in the function we pass the cell id and the column number
td.onclick=function(obj,val1,val2){
return function(){
obj.callWindow(val1,val2);
}
}(this,id,colN);
}else
{
if((this.f_pU=="1" && node.data[i].a.indexOf("u")!=-1)||(this.f_State=="1"))
{
td.onclick=function(thiz,val1,val2){
return function(){thiz.updateRecord(val1);};
}(this,id);
}else
{
td.style.cssText="cursor: default;";
}
}
tr.appendChild(td);
}
colN++;
}
theTable.tBodies[0].appendChild(tr);
} }
this.updateSize(); this.updateSize();
} }
@ -1466,11 +1462,9 @@ class SRec
} }
} }
//find the node cdata in the data by the record id and column name //Get column number by name
getDataC(id,col) getColN(name){
{ let i=-1;
let i=0;
let b=false;
//determine the sequence number of the column //determine the sequence number of the column
let node=findNodeOnPath(this.nodeMetadata,"type/objects-list"); let node=findNodeOnPath(this.nodeMetadata,"type/objects-list");
let nodeCol = node.firstChild; let nodeCol = node.firstChild;
@ -1479,73 +1473,66 @@ class SRec
if(nodeCol.nodeName=="column") if(nodeCol.nodeName=="column")
{ {
if(nodeCol.getAttribute("n")==col){ if(nodeCol.getAttribute("n")==col){
b=true;
break; break;
} }
i++; i++;
} }
nodeCol = nodeCol.nextSibling; nodeCol = nodeCol.nextSibling;
} }
if(!b)return null; return i;
//we search for value in result set
node=findFirstNode(this.f_nodeData, 'type');
let nodeRec=findNodeOnAttribute(node, 'record', 'id', id);
return findNodeOnNum(nodeRec,"#cdata-section",i);
} }
//find the value in the result set by the id of the record and the name of the column //find the value in the result set by the id of the record and the name of the column
getData(id,col) getData(id,col)
{ {
if(findNode(this.nodeMetadata,'type').getAttribute("ObjectID")==col) return id; if(findNode(this.nodeMetadata,'type').getAttribute("ObjectID")==col)
let cdt=this.getDataC(id,col); return id;
if(cdt!=null) return cdt.nodeValue; else return ''; let pos=this.getColN(col);
if(pos>=0){
for(let i=0;i<this.f_nodeData.data.length;i++){
if(this.f_nodeData.data[i].id=id){
return this.f_nodeData.data[i].row[pos];
}
}
}
return '';
} }
//look for a string by id and update the values (TODO consecutively without hidden fields) //look for a string by id and update the values (TODO consecutively without hidden fields)
updateRows(node) updateRows(node)
{ {
//We sort through the received records and update the values //We sort through the received records and update the values
let nodeRecord = findNode(node,"type").firstChild for(let i=0;i<node.data.length;i++)
while (nodeRecord != null)
{ {
if(nodeRecord.nodeName=="record") let id=node.data[i].id;
let tr=document.getElementById(id+'_'+this.uid);
if (tr==null)
{ {
let ii=0; this.insertRows(node,false); //If not then insert
let jj=0; }else //Update fields if editing
let id=nodeRecord.getAttribute("id"); {
let tr=document.getElementById(id+'_'+this.uid); //Updating data in a data object
for(let ii=0;ii<this.f_nodeData.data.length;ii++){
if (tr==null) if(this.f_nodeData.data[ii].id==id) {
this.f_nodeData.data[ii].row=node.data[i].row;
}
}
//Updating data in an HTML table
tr.style.textDecoration="underline";
for(let j=0;j<node.data[i].row.length;j++)
{ {
this.insertRows(node,false); //If not then insert if(this.masCL[j].getAttribute("visible")!="0")
}else
{
tr.style.textDecoration="underline";
let cdataNode = nodeRecord.firstChild;
while (cdataNode!=null)
{ {
if (cdataNode.nodeName=="#cdata-section") while(tr.childNodes[j+2].childNodes[0]) {
{ tr.childNodes[j + 2].removeChild(tr.childNodes[j + 2].childNodes[0]);
let cd=this.getDataC(id,this.masCL[ii].getAttribute("n"));
if(cd!=null) cd.nodeValue=cdataNode.nodeValue;
if(this.masCL[ii].getAttribute("visible")!="0")
{
while(tr.childNodes[jj+2].childNodes[0])
tr.childNodes[jj+2].removeChild(tr.childNodes[jj+2].childNodes[0]);
tr.childNodes[jj+2].appendChild(document.createTextNode(cdataNode.nodeValue));
jj++;
}
ii++;
} }
cdataNode = cdataNode.nextSibling; let textNode;
if(node.data[i].row[j]!=null) textNode=document.createTextNode(node.data[i].row[j]);
else textNode=document.createTextNode("");
tr.childNodes[j+2].appendChild(textNode);
} }
} }
} }
nodeRecord = nodeRecord.nextSibling;
} }
} }
@ -1689,8 +1676,9 @@ class SRec
//Rebuild sequential numbering of rows (first column) //Rebuild sequential numbering of rows (first column)
let theTable = document.getElementById('thetable'+this.uid); //data table let theTable = document.getElementById('thetable'+this.uid); //data table
for(let i=1;i<theTable.rows.length;i++) for(let i=1;i<theTable.rows.length;i++)
{while (theTable.rows[i].cells[0].childNodes[0]) //delete all childs {
{theTable.rows[i].cells[0].removeChild(theTable.rows[i].cells[0].childNodes[0]); while (theTable.rows[i].cells[0].childNodes[0]) //delete all childs
{ theTable.rows[i].cells[0].removeChild(theTable.rows[i].cells[0].childNodes[0]);
} }
theTable.rows[i].cells[0].appendChild(document.createTextNode(i)); theTable.rows[i].cells[0].appendChild(document.createTextNode(i));
} }

View File

@ -1020,7 +1020,7 @@ function delChild(obj)
function applyNodeToNode(first, second, name) function applyNodeToNode(first, second, name)
{ {
if(first===null || second===null || name ===null){ if(first===null || second===null || name ===null){
console.error("first="+first+" second="+second+" name="+name); log.error("first="+first+" second="+second+" name="+name);
return; return;
} }
//Если есть совпадающие узлы то передаём в рекурсию если нет то просто копируем //Если есть совпадающие узлы то передаём в рекурсию если нет то просто копируем
@ -1057,10 +1057,9 @@ function applyNodeToNode(first, second, name)
/*function applyObjectToObject(first, second, name){ /*function applyObjectToObject(first, second, name){
if(first===null || second===null || name ===null){ if(first===null || second===null || name ===null){
console.error("first="+first+" second="+second+" name="+name); log.error("first="+first+" second="+second+" name="+name);
return; return;
} }
}*/ }*/
function escapeRegExp(str) { function escapeRegExp(str) {
@ -1114,39 +1113,97 @@ class TRequest
} }
processReqChange(xmlHttpRequest,url,xmlString) processReqChange(xmlHttpRequest,url,xmlString)
{
if(typeof(xmlHttpRequest.status)=='undefined' || xmlHttpRequest.status == 200)
{
if(xmlHttpRequest.responseXML!=null) {
//if(typeof(xmlHttpRequest.responseXML)=='undefined' && xmlHttpRequest.contentType.match(/\/xml/)) //For IE XDomainRequest
// xmlHttpRequest.responseXML=CreateXMLDOC(xmlHttpRequest.responseText);
let xmldoc = xmlHttpRequest.responseXML;
if (xmldoc == null) {
alert2(trt('Alert'), trt('Wrong_XML_document') + "!\nXML=(" + xmlHttpRequest.responseText + ')\nURL=(' + url + ')\nxmlString=(' + xmlString + ')');
return;
}
let node = xmldoc.documentElement;
if ((node == null) || (node.getAttribute("fn") == null)){
alert2(trt('Error'), trt('No_data')+"! \n" + xmlHttpRequest.responseText);
}else {
let fn = node.getAttribute("fn");
if (this.winObj != null) {
this.winObj.applyReq(this, fn, node, xmldoc, this.winObj);
return null;
}
}
}else{
let obj = JSON.parse(xmlHttpRequest.responseText);
if(obj==null) {
alert2(trt('Alert'), trt('Wrong_JSON_document') + "!\nJSON=(" + xmlHttpRequest.responseText + ')');
return;
}
if(this.winObj!=null)
{
this.winObj.applyReq(this,obj.fn,obj,null,this.winObj);
return null;
}
}
}else
{
if(confirm(trt('Failed_to_get_data')+"\n URL: "+url+"\n"+xmlHttpRequest.statusText+trt('Repeat_request')+'?'))
{
this.callServer(url,xmlString);
};
}
return null;
}
/*processReqChange(xmlHttpRequest,url,xmlString)
{ {
//if (typeof(xmlHttpRequest.readyState)=='undefined' || xmlHttpRequest.readyState == 4) //if (typeof(xmlHttpRequest.readyState)=='undefined' || xmlHttpRequest.readyState == 4)
//{ //{
if(typeof(xmlHttpRequest.status)=='undefined' || xmlHttpRequest.status == 200) if(typeof(xmlHttpRequest.status)=='undefined' || xmlHttpRequest.status == 200)
{ {
if(typeof(xmlHttpRequest.responseXML)=='undefined' && xmlHttpRequest.contentType.match(/\/xml/)) //For IE XDomainRequest alert(JSON.stringify(xmlHttpRequest));
xmlHttpRequest.responseXML=CreateXMLDOC(xmlHttpRequest.responseText); if(typeof(xmlHttpRequest.responseXML)=='undefined') {
if(xmlHttpRequest.contentType.match(/\/xml/)) {
//загрузился xml документ начинаем его разбирать (по id функции в документе) xmlHttpRequest.responseXML = CreateXMLDOC(xmlHttpRequest.responseText);
let xmldoc = xmlHttpRequest.responseXML; if(xmlHttpRequest.responseXML==null) {
if(xmldoc==null){ alert2(trt('Alert'), trt('Wrong_XML_document') + "!\nXML=(" + xmlHttpRequest.responseText + ')\nURL=(' + url + ')\nxmlString=(' + xmlString + ')');
alert2(trt('Alert'),trt('Wrong_XML_document')+"!\nXML=("+xmlHttpRequest.responseText+')\nURL=('+url+')\nxmlString=('+xmlString+')'); return;
return; }
} //загрузился xml документ начинаем его разбирать (по id функции в документе)
let node = xmlHttpRequest.responseXML.documentElement;
let node = xmldoc.documentElement; if((node==null)||(node.getAttribute("fn")==null)) alert(trt('Error')+"\n"+trt('No_data')+"!\n"+xmlHttpRequest.responseText);
if((node==null)||(node.getAttribute("fn")==null)) alert(trt('Error')+"\n"+trt('No_data')+"!\n"+xmlHttpRequest.responseText); else
else
{
//alert("XML=\n"+getXMLNodeSerialisation(node));
let fn = node.getAttribute("fn");
if(this.winObj!=null)
{
//this.winObj.alert("Принятый браузером XML=\n"+getXMLNodeSerialisation(node));
/* каждый слушатель должен сам реализовать
* if (fn==-1)
{ {
alert(findFirstNode(node,'#cdata-section').nodeValue); let fn = node.getAttribute("fn");
}else*/ if(this.winObj!=null)
this.winObj.applyReq(this,fn,node,xmldoc,this.winObj); {
return null; this.winObj.applyReq(this,fn,node,xmldoc,this.winObj);
}else if(fn==0) alert(findFirstNode(node,'#cdata-section').nodeValue); return null;
}else if(fn==0) alert(findFirstNode(node,'#cdata-section').nodeValue);
}
}else if(xmlHttpRequest.contentType.match(/\/json/)){
xmlHttpRequest.responseXML = JSON.parse(xmlHttpRequest.responseText);
if(xmlHttpRequest.responseXML==null) {
alert2(trt('Alert'), trt('Wrong_JSON_document') + "!\nJSON=(" + xmlHttpRequest.responseText + ')\nURL=(' + url + ')\njsonString=(' + xmlString + ')');
return;
}
//загрузился xml документ начинаем его разбирать (по id функции в документе)
let node=xmlHttpRequest.responseXML;
if((node==null)||(node.fn==null)) alert(trt('Error')+"\n"+trt('No_data')+"!\n"+xmlHttpRequest.responseText);
else
{
if(this.winObj!=null)
{
this.winObj.applyReq(this,node.fn,node,null,this.winObj);
return null;
}else if(fn==0) alert(findFirstNode(node,'#cdata-section').nodeValue);
}
}
} }
}else }else
{ {
if(confirm(trt('Failed_to_get_data')+"\n URL: "+url+"\n"+xmlHttpRequest.statusText+"\nПовторить запрос?")) if(confirm(trt('Failed_to_get_data')+"\n URL: "+url+"\n"+xmlHttpRequest.statusText+"\nПовторить запрос?"))
@ -1156,7 +1213,7 @@ class TRequest
} }
//} //}
return null; return null;
} }*/
}; };
/** Класс асинхронных запросов к серверу /** Класс асинхронных запросов к серверу

10718
metadata/jquery.js vendored

File diff suppressed because one or more lines are too long