quarta-feira, 2 de abril de 2014

Buscando informações no Names com ajax e json


1º Criar a bilbioteca de javascript de  Ajax

#############################################################################

function AJAX(url, metodo, params, processa, modo) {
 this.url = url;
 this.metodo = (metodo)? metodo : 'GET';
 this.params = (metodo='GET')? null : params;
 this.processaresultado = processa;
 this.modo = (modo) ? modo : 'T';
 if(this.modo!='T' && this.modo!='X'){
  this.modo='T';
 }
 this.conectar();
}

AJAX.prototype = {
conectar: function() {
  if(this.url==undefined || this.url==''){
   return;
  }
  this.httprequest = null;
  if (window.XMLHttpRequest){
  this.httprequest = new XMLHttpRequest();
  if(this.metodo=='POST')
   this.httprequest.setRequestHeader('Content-length', params.length );
  } else if (window.ActiveXObject) {
   try {
    this.httprequest = new ActiveXObject("Msxml2.XMLHTTP");
   } catch(e){
    try{
     this.httprequest = new ActiveXObject("Microsoft.XMLHTTP");
    } catch(e) {}
   }
  }
  if(this.httprequest!=null && this.httprequest!=undefined) {
   var obj = this;
   this.httprequest.onreadystatechange = function() {
    obj.processaretorno.call(obj);
   }
   this.httprequest.open(this.metodo,this.url,true);
   this.httprequest.send(this.params);
  }
 },
processaretorno : function(){
  if(this.httprequest.readyState==4){
   if(this.httprequest.status==200) {
    var resp = (this.modo=='T')? this.httprequest.responseText : this.httprequest.responseXML;
    if(this.processaresultado!=null){
     this.processaresultado(resp);
    } else {
     document.write(resp);
    }
   } else {
    this.processaerro();
   }
  }
 },
processaerro: function() {
  alert(this.httprequest.status + ' - ' + this.httprequest.statusText + ' :-> ' + this.url);
 }
}
function getHash() {
 return new Date().getTime();
}
##############################################################################

2º  Criar função que executara a chamada do agente lotusscript/java para realizar a consulta e criar o objeto Json


##############################################################################


//Busca dados por Chave
function buscaDadosPorChave(chave,t_funcao){
// S => solicitante
// B => beneficiario

if(chave == null) return;

if(chave.length != 4){
alert("A chave " + chave + " é inválida. A chave deverá conter 4 dígitos.");
return false;
}else{
var tdoc = new TDocument();
var ajax = new AJAX();
vurl = "http://"+ tdoc.server+ "/" + tdoc.pathname +"/ag_BuscaDadosporChaveWeb?OpenAgent&chave="+chave+"&hash="+getHash();
ajax.url = vurl;
ajax.modo = 'T';
ajax.metodo ="GET"
ajax.processaresultado = t_funcao
ajax.conectar();
}
}
//Fim da Busca por Chavee

##############################################################################

3º criação do agente p/buscar as informações no Names/base de informações de usuário


Sub Initialize
On Error GoTo error_handler

Dim m_Session As New NotesSession
Dim m_docContext As NotesDocument

Set m_docContext = m_Session.DocumentContext

Dim t_strChave As String
t_strChave = f_retornaParametroURL (m_docContext.Query_String(0),"chave")

Dim m_docPerson As NotesDocument
Set m_docPerson = getDocPersonNames(t_strChave)


'cria o objeto json
Print "Content-type: text/html;charset=utf-8"
Print "{"

If m_docPerson Is Nothing Then
Print |"localizado":"0",|
Print |"chave":"não encontrado",|
Print |"nomenotes":"não encontrado",|
Print |"orgao":"não encontrado",|
Print |"ramal":"não encontrado",|
Print |"matricula":"não encontrado",|
Print |"identificacao":"não encontrado",|
Print |"situacaocontratual":"não encontrado",|
Print |"funcao" :"não encontrado"|
Else
Dim t_name As NotesName
Set t_name = New NotesName(m_docPerson.ca_nomeNotes(0))

Set nome = New NotesName(m_docPerson.FullName(0))
Print |"localizado":"1",|
Print |"chave":"|+ EscapeJS(m_docPerson.ca_chave(0)) +|",|
Print |"nomenotes":"|+ EscapeJS(t_name.Abbreviated) +|",|
Print |"orgao":"|+ EscapeJS(m_docPerson.ca_orgaoMenor(0))+|",|
Print |"ramal":"| + EscapeJS(m_docPerson.ca_ramalSITEL(0))+|",|
Print |"matricula":"| + EscapeJS(m_docPerson.ca_matricula(0))+|",|
Print |"identificacao":"| + EscapeJS(m_docPerson.ca_identificacao(0))+|",|
Print |"situacaocontratual":"| + EscapeJS(retornaVinculo(m_docPerson.ca_vinculo(0)))+|",|
Print |"regiao":"|+ EscapeJS(m_docPerson.ca_regiao(0))+|",|
Print |"funcao":"| + EscapeJS(m_docPerson.ca_funcao(0))+|"|

End If

Print "}"

Exit Sub

Error_Handler:
'Print||
Print {}
Call LogError()
Exit sub
End Sub

Function f_retornaParametroURL(ByVal t_qry As String,ByVal t_param As String ) As String
On Error GoTo trataerro

Dim i,j As Integer
Dim result As String
i = InStr(1, t_qry, t_param)
result= ""
If i > 0 Then
j = InStr(i, t_qry, "&")
If j > 0 Then
result$ = Mid(t_qry, i + Len(t_param) + 1, (j - 1) - (i + Len(t_param)))
Else
result$ = Mid(t_qry, i + Len(t_param) + 1)
End If
End If
f_retornaParametroURL = result

trataerro:
Call AddToStackTrace()
End Function




Function EscapeJS(ByVal a_strOrigem As String) As String
On Error GoTo ErrorHandler
Dim t_astrBusca(0 To 1) As String
t_astrBusca(0) = |\|
t_astrBusca(1) = |"|
Dim t_astrSubst(0 To 1) As String
t_astrSubst(0) = |\\|
t_astrSubst(1) = |\"|

Dim t_astrSource(0 To 0) As String
t_astrSource(0) = a_strOrigem

Dim t_astrRet As Variant
t_astrRet = Replace(t_astrSource, t_astrBusca, t_astrSubst)

EscapeJS = t_astrRet(0)

Exit Function
ErrorHandler:
Call AddToStackTrace()
End Function



##############################################################################

4 º Função para popular o documento web.

function atualizaCamposSolicitante(txt){

var obj = eval ("(" + txt + ")");

if (obj.localizado == '0') {
alert('Chave não encontrada na base de pessoal.\nFavor informar a chave correta.');
document.getElementById("ca_PEDSolicitanteLocalizado").value = "0";
}else{
document.getElementById("ca_PEDSolicitanteLocalizado").value = "1";
}

document.getElementById("PEDsolicitanteTX").value = obj.nomenotes;
document.getElementById("PEDsolicitantelotacaoTX").value = obj.orgao;
document.getElementById("PEDsolicitanteramalTX").value = obj.ramal;
document.getElementById("PEDfuncaoTX").value = obj.funcao;


}

function atualizaCamposBeneficiario(txt){

var obj = eval ("(" + txt + ")");

if (obj.localizado == '0') {
alert('Chave não encontrada na base de pessoal.\nFavor informar a chave correta.');
document.getElementById("ca_PEDbeneficiarioLocalizado").value = "0";
}else{
document.getElementById("ca_PEDbeneficiarioLocalizado").value = "1";
}

document.getElementById("ca_PEDbeneficiarioNomeTX").value = obj.nomenotes;
document.getElementById("ca_PEDbeneficiarioNomeTX").value = obj.nomenotes;
document.getElementById("ca_PEDbeneficiarioUnidadeTX").value = obj.orgao;
document.getElementById("ca_PEDbeneficiarioCargoTX").value = obj.funcao;
document.getElementById("ca_PEDbeneficiarioRamalTX").value = obj.ramal;
document.getElementById("ca_PEDbeneficiarioRegiaoTX").value = obj.regiao;
document.getElementById("ca_PEDbeneficiarioMatriculaTX").value = obj.matricula;
document.getElementById("ca_PEDbeneficiarioIdentificadorTX").value = obj.identificacao;
document.getElementById("ca_PEDbeneficiarioSContratualTX").value = obj.situacaocontratual;

}


##############################################################################
5º Chamada da ação
'// do exemplo ficou no evento onBlur
'// informa a chave e a funcao desejada

buscaDadosPorChave(this.value,funcao)

##############################################################################

Nenhum comentário:

Postar um comentário