Visualizzazione dei risultati da 1 a 2 su 2
  1. #1
    Utente di HTML.it L'avatar di kluster
    Registrato dal
    Jul 2003
    Messaggi
    1,288

    utilizzare come callback una funzione interna dell'oggetto

    Dunque, studiando ajax prima mi sono sviluppato semplici test tramite funzioni separate. Ora sto cercando di racchiudere le funzioni all'interno di un oggetto tramite questo codice:
    codice:
    function xmlHttpObject() 
    {
    	var xmlObj;
    	try	{xmlObj= new ActiveXObject("Msxml2.XMLHTTP");} 
    	catch (e) 
    	{
    		try{xmlObj= new ActiveXObject("Microsoft.XMLHTTP");;} 
    		catch (oc){xmlObj 				= null;}
    	}
    	if(!xmlObj && typeof XMLHttpRequest != "undefined")
    	{
    		xmlObj 							= new XMLHttpRequest();	
    	}
    	this.obj							= xmlObj;
    	this.innerXML						= null;
    	this.elaborateFunction				= null;
    	this.callback = function callback()
    	  {
    		if (this.obj.readyState == 4) 
    		{
    			if (this.obj.status == 200) 
    			{
    				this.innerXML = this.obj.responseXml;
    				eval(this.eleborateFunction);
    			} 
    			else 
    			{
    				this.error = "Errore nel caricamento dati: "+ this.obj.statusText;
    			}
    		}
    	  }
    	this.open = function open(url,method)
    	 {
    		this.obj.onreadystatechange = this.callback;
    		if (method.toLowerCase() == "post")
    		{
    			this.obj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    			this.obj.open("POST", url, true);
    		}
    		else
    		{
    			this.obj.open("GET", url, true);
    		}
    		this.obj.send(null);
    	}
    	
    	
    	return (this);
    }
    Il mio intento è creare una classe riutilizzabile in modo da avere nella variabile innerXml l'xml generato dalla pagina lato server per poi poterla rielaborare tramite la funzione internta elaborateFunction.
    In questo modo lanciando l'oggetto si è liberi di manipolare l'output xml in maniera distaccata tramite proprie funzioni.
    il problema (sara' la giornata piovosa) mi sono arenato
    nella parte in grassetto: this.obj.onreadystatechange = this.callback
    assegno la funzione interna callback al caricamento dell'xml del oggetto Xml Request.
    All'entrata della funzione l'oggetto perde il suo valore e firefox mi riporta un laconico this.obj.status has no properties.

    Nel frattempo mi ci continuo a rompere la testa ma se qualcuno ha un suggerimento è ben accetto.

  2. #2
    Utente di HTML.it L'avatar di kluster
    Registrato dal
    Jul 2003
    Messaggi
    1,288
    ok, ce l'ho scampata.
    Pubblico lo script nel caso possa tornare utile a qualcuno.
    Se qualcuno + esperto di me ha suggerimenti su velocizzazione della classe o su metodi che possono essere migliorati stilisticamente sono ben accetti suggerimenti e critiche.

    Function xmlHttpObject() restituisce un oggetto XmlHttpRequest() crossbrowser (almeno secondo le mie prove)
    che ha i seguenti metodi.

    open(url,metodo,funzione callback)
    url è la pagina dove risiede il codice server-side da eseguire
    metodo puo essere GET o POST
    funzione callback è una funzione custom che si innesca al caricamento dell'XmlDomDocument


    getXmlDocument()
    restituisce un oggetto valido Xml Dom Document per poter essere rielaborato secondo i propri gusti

    per effettuare i test di debug ho creato un layer crossbrowser (anche grazie alla DHTML API 1k di http://www.dithered.com/)
    Function LayerCB restituisce un riferimento crossbrowser al layer specificato.
    metodi:
    show() mostra il livello
    hide() nasconde il livello
    write()(sovra)scrive l'html all'interno del layer (non supportata da Opera e IE 4 per Mac
    setZIndex(value) imposta il nuovo zindex specificato in value
    setX(value) imposta la posizione orizzontale specificata in value
    setY(value) imposta la posizione verticale specificata in value
    setWith(value)imposta la larghezza del layer specificata in value
    setHeight(value) imposta l'altezza del layer specificata in value

    ecco un esempio completo:
    codice:
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>Test Ajax</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <script language="JavaScript" type="text/javascript">
    //<![CDATA[
    // Function per creare un oggetto layer crossbrowser
    function LayerCB(elementName,root)
    {	
    	opera = navigator.userAgent.indexOf('Opera')!=-1;
    	if(document.layers)
    	{	
    		root		=(root)?root:self;
    		var LNs		=root.document.layers;
    		if(LNs[elementName]) {this.o = LNs[elementName];}
    		for(var i=0;i<LNs.length;) {found=LayerCB(elementName,LNs[i++]);}
    		this.o 		=  found;
    	}
    	if(document.all){this.o = document.all[elementName];}
    	if (document.getElementById){this.o = document.getElementById(elementName);}
    	this.write		= function write(html)
    	                  {
    						 	if(document.layers){with (this.o){document.open();document.write(html);document.close();}}
    							else {if(this.o.innerHTML) {this.o.innerHTML=html;}}
    					  }
    	this.show		= function show(){document.layers?this.o.visibility='show':this.o.style.visibility='visible';}
    	this.hide		= function hide(){document.layers?this.o.visibility='hide':this.o.style.visibility='hidden';}		
    	this.setZIndex  = function setZIndex(value){document.layers?this.o.zIndex=value:this.o.style.zIndex=value;}			  
    	this.setX		= function setX(value){document.layers?this.o.left=value:opera?this.o.style.pixelLeft=value:this.o.style.left=value+"px";}
    	this.setY		= function setY(value){document.layers?this.o.top=value:opera? this.o.style.pixelTop=value:this.o.style.top=value+"px";}
    	this.setWidth	= function setWidth(value){document.layers?this.o.clip.width=value:opera?this.o.style.pixelWidth=value:this.o.style.width=value+"px";}
    	this.setHeight	= function setHeight(value){document.layers?this.o.clip.height=value:opera?this.o.style.pixelHeight=value:this.o.style.height=value+"px";}
    	return this;					  
    }
    //funzione per ottenere un oggetto valido XmlHttpRequest crossbrowser
    function xmlHttpObject() 
    {
    	var xmlObj;
    	try	{xmlObj= new ActiveXObject("Msxml2.XMLHTTP");} 
    	catch (e) 
    	{
    		try{xmlObj= new ActiveXObject("Microsoft.XMLHTTP");;} 
    		catch (oc){xmlObj 				= null;}
    	}
    	if(!xmlObj && typeof XMLHttpRequest != "undefined")
    	{
    		xmlObj 							= new XMLHttpRequest();	
    	}
    	this.reqObj							= xmlObj;
    	
    	var innerDocXML						= null;
    	this.getXmlDocument					= function getXml() {return innerDocXML}
    	this.open = function open(url,method,workFunction)
    	 {
    		xmlObj.onreadystatechange = function ()
    									  {
    										if (xmlObj.readyState == 4) 
    										{
    											if (xmlObj.status == 200) 
    											{
    												innerDocXML 			= xmlObj.responseXML;
    												this.reqObj				= xmlObj;
    												eval(workFunction);
    											} 
    											else 
    											{
    												this.error = "Errore nel caricamento dati: "+ xmlObj.statusText;
    											}
    										}
    									  }
    
    		if (method.toLowerCase() == "post")
    		{
    			xmlObj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    			xmlObj.open("POST", url, true);
    		}
    		else
    		{
    			xmlObj.open("GET", url, true);
    		}
    		xmlObj.send(null);
    	}
    	
    	return (this);
    }
    //inizializzo la variabile
    var objXmlRequest = new xmlHttpObject();
    //una semplice funzione di testing:
    //parametri: URL - METODO- LA FUNZIONE DI CALLBACK()
    function run(url,method,funcElaboraXml){objXmlRequest.open(url,method,funcElaboraXml);}
    function readXml()
    {	
    	buffer = "";
    	//nella funzione di callback la chiamata getXml restituisce un oggetto Xml Dom Object
    	 var rootDocument = objXmlRequest.getXmlDocument();
    	 var items = rootDocument.getElementsByTagName("record");
    	 for (var i = 0; i < items.length; i++)
    	 {
    	 	buffer += items[i].firstChild.nodeValue + "
    ";
    	 }
    	 var lay = LayerCB('Layer1');
    	 lay.show();
    	 lay.write(buffer);
    }
    //]]>
    </script>
    <style type="text/css">
    #Layer1
    {
    	position:absolute;
    	background:#DDDDDD;
    	overflow:visible;
    	border:1px solid black;
    	visibility:hidden;
    }
    </style>
    </head>
    
    <body>
    test :
    
    <div id="Layer1">
    </div>
    </body>
    </html>
    Nell'esempio viene inizializzata la variabile di riferimento all'XmlHttpRequest()
    La funzione run eseque il metodo open passando l'url, il metodo e la funzione che elabora l'xml (readXml())
    Nella funzione readXml ho fatto un semplice elenco dei nodi, l'oggetto restituito dalla funzione getXmlDocument() è di tipo XmlDom Document e quindi potete manipolarlo come vi pare. Per un riferimento sui metodi e proprieta' del Xml Dom Document: http://www.devguru.com/Technologies/..._document.html

    la pagina testAjaxOutput.asp è una semplice pagina di debug da ampliare:
    codice:
    <%
    Response.ContentType="text/xml"
    Response.Write("<?xml version=""1.0"" encoding=""UTF-8""?>")
    Response.Write("<output>")
    Response.Write("<record>Query di interrogazione con paramentro id = " & Request("id") & "</record>")
    Response.Write("</output>")
    %>
    un esempio funzionante qui

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.