Visualizzazione dei risultati da 1 a 6 su 6
  1. #1
    Utente di HTML.it L'avatar di Akito
    Registrato dal
    Nov 2005
    Messaggi
    101

    [AJAX] oggetti e funzioni con parametri

    Ciao a tutti,
    ho un piccolo problema da sottoporvi. Vorrei parametrizzare la funzione handleResponse() che vedete qui sotto in modo tale da decidere in che oggetto HTML inserire il testo che mi arriva dalla risposta del server.
    Il codice è questo:

    function createObject() {
    var tipo_richiesta;
    var browser = navigator.appName;
    if(browser == "Microsoft Internet Explorer") {
    tipo_richiesta = new ActiveXObject("Microsoft.XMLHTTP");
    }else{
    tipo_richiesta = new XMLHttpRequest();
    }
    return tipo_richiesta;
    }

    var http = createObject();

    function handleResponse() {
    if(http.readyState < 4) {
    document.getElementById("status").innerHTML = "Loading...";
    }
    if(http.readyState == 4) {
    if(http.status == 200) {
    document.getElementById("status").innerHTML = http.responseText;
    } else {
    document.getElementById("status").innerHTML = http.status;
    }
    }
    }

    function sendGet(valore) {
    http.open('GET', 'file.php?variabile='+valore, true);
    http.onreadystatechange = handleResponse;
    http.send(null);
    }




    e vorrei che handleResponse() diventasse così ma non funziona su tutti i Browser !

    function handleResponse(dest) {
    if(http.readyState < 4) {
    document.getElementById(dest).innerHTML = "Loading...";
    }
    if(http.readyState == 4) {
    if(http.status == 200) {
    document.getElementById(dest).innerHTML = http.responseText;
    } else {
    document.getElementById(dest).innerHTML = http.status;
    }
    }
    }

    function sendGet(valore, dest) {
    http.open('GET', 'file.php?variabile='+valore, true);
    http.onreadystatechange = handleResponse(dest); // questa è la riga che da problemi
    http.send(null);
    }


    Che mi consigliate ?
    Come faccio ad assegnare al metodo http.onreadystatechange la funzione handleResponse passandole anche il parametro dest ?

    Grazie mille
    Ciao
    Akito

  2. #2
    Utente di HTML.it L'avatar di pietro09
    Registrato dal
    Jan 2002
    Messaggi
    10,116
    forse qui trovi degli spunti:
    in pratica, onload può essere o una funzione di ritorno o un ID di destinazione

    codice:
    //========================== inizio new ajax ==================================
    
    /*--------------------------------------------------------------------------------------------------------------
    									PARAMETRI
    									---------
    url				=	indirizzo della pagina di action, es: url = "pagina.asp?variabile=valore"
    					può essere '?'. In tal caso viene considerata la pagina corrente
    			
    onload			=	può essere l'indirizzo della funzione di ritorno, un id valido o un oggetto valido,
    					un vettore di id validi, un vettore di oggetti validi.
    					se = null, non viene recuperato il dato di ritorno, ma la pagina server è richiamata lo stesso
    					nella funzione di callback si recuperano responseText o responseXML con
    					var t = this.request.responseText; var tx = this.request.responseXML;
    					
    parameters		=	tipo "variabile1=valore1&variabile2=valore2". E' opzionale perchè i parametri
    					possono essere passati nell'url
    
    onerror			=	funzione richiamata in caso di errore. se omessa viene richiamata la funzione di
    					errore predefinita 	defaultError
    									
    method			=	'get' o 'post' default -> post
    -----------------------------------------------------------------------------------------------------------------*/
    function ajax(url, onload, parameters, onerror, method)
    {
    	this.request = null;
    	this.exception = null;
    	this.onload = onload;
    	this.onerror = (onerror) ? onerror : this.defaultError;
    	this.loadXMLDoc(url, parameters, method);
    }
    
    ajax.prototype = 
    {
    	loadXMLDoc: function(url, parameters, method, asynchronous)
    	{
    		parameters = (parameters == undefined)? "" : parameters;
    		asynchronous = (asynchronous == undefined)? true : asynchronous;
    		if(method == undefined)
    		{
    			method = "post";
    		}
    		else
    		{
    			method = method.toLowerCase( );
    			if(method != "post" && method != "get")
    			{
    				method = "post";
    			}
    			else if(method == "get")
    			{
    				if(url.indexOf("?") == -1)
    					url += "?" + parameters;
    				else
    					url += "&" + parameters;
    			}
    		}
    		
    		
    				
    		if (window.XMLHttpRequest)
    		{
    			this.request = new XMLHttpRequest();
    		} 
    		else if (window.ActiveXObject)
    		{
    			this.request = new ActiveXObject("Microsoft.XMLHTTP");
    		}
      
    		if (this.request)
    		{
    			try
    			{
    				var loader = this;
    				this.request.onreadystatechange = function()
    				{
    					loader.onReadyState.call(loader);
    				}
    				this.request.open(method, url, asynchronous);
    				if(method == "post")
    				{
    					this.request.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    					this.request.setRequestHeader('Content-length',parameters.length);
    					this.request.setRequestHeader('Connection', 'close');
    					this.request.send(parameters);
    				}
    				else if(method == "get")
    				{
    					this.request.send(null);
    				}
    			}
    			catch (ex)
    			{
    				this.exception = ex;
    				this.onerror.call(this);
    			}
    		}
    	},
    
    	onReadyState: function()
    	{
    		var req = this.request;
    		var ready = req.readyState;
    		
    		if (ready == 4)
    		{
    			var httpStatus = req.status;
    			
    			if (httpStatus == 200 || httpStatus == 0)
    			{
    				if(this.getTypeParameter(this.onload) == 1 /*funzione di ritorno*/) {this.onload.call(this);}
    				else if(this.getTypeParameter(this.onload) == 2 /*identificativo tag che supporta innerHTML*/){document.getElementById(this.onload).innerHTML = this.request.responseText;}
    				else if(this.getTypeParameter(this.onload) == 3 /*identificativo tag che supporta value*/){document.getElementById(this.onload).value = this.request.responseText;}
    				else if(this.getTypeParameter(this.onload) == 4 /*oggetto tag che supporta innerHTML*/){this.onload.innerHTML = this.request.responseText;}
    				else if(this.getTypeParameter(this.onload) == 5 /*oggetto tag che supporta value*/){this.onload.value = this.request.responseText;}
    				else if(this.getTypeParameter(this.onload) == 6 /*vettore di identificativi-elementi*/)
    				{
    				/**/
    					var t = this.request.responseText;
    					var tx = this.request.responseXML;
    					
    					if(!this.isXML(tx))
    					{
    						//testo. i campi sono separati da "|"
    						var v = t.split("|");	
    					}
    					else 
    					{
    						//xml
    						var radice = tx.documentElement;
    						var items = radice.getElementsByTagName("record");
    						var n = items.length;
    						
    						if(n == 1)
    						{
    							var nodi = items[0].childNodes;
    							var numero_nodi = nodi.length;
    							var v = [];
    							for(var i = 0; i < numero_nodi; i++)
    							{
    								if(nodi[i].tagName != undefined)
    								{
    									v[v.length] = nodi[i].firstChild.nodeValue;
    								}
    							}
    						}
    					
    					}
    					
    					var target = this.onload;
    					if(v.length == target.length)
    					{
    						for(var i = 0; i < v.length; i++)
    						{
    							if(this.getTypeParameter(target[i]) == 2)
    							{
    								document.getElementById(target[i]).innerHTML = v[i];
    							}
    							else if(this.getTypeParameter(target[i]) == 3)
    							{
    								document.getElementById(target[i]).value = v[i];
    							}
    							else if(this.getTypeParameter(target[i]) == 4)
    							{
    								target[i].innerHTML = v[i];
    							}
    							else if(this.getTypeParameter(target[i]) == 5)
    							{
    								target[i].value = v[i];
    							}
    						}
    					
    					}
    				
    				/**/
    				}
    				
    			}
    			else
    			{
    				this.onerror.call(this);
    			}
    		}
    	},
    
    	defaultError:function()
    	{
    		var a = [];
    		a[0] = (this.exception)? this.exception.message : "";
    		
            try
            {
    	        a[1] = this.request.readyState;
            }
            catch(ex)
            {
    	        a[1] = "";
            }		
    		
            try
            {
    	        a[2] = this.request.status ;
            }
            catch(ex)
            {
    	        a[2] = "";
            }		
    		
            try
            {
    	        a[3] = this.request.statusText;
            }
            catch(ex)
            {
    	        a[3] = "";
            }		
    		
            try
            {
    	        a[4] = this.request.getAllResponseHeaders();
            }
            catch(ex)
            {
    	        a[4] = "";
            }		
    		
    		
    		alert("ERRORE NELLA TRASMISSIONE DATI!" 
            + ((a[0]=="")?"": "\n\n" + a[0] )
    		+ ((a[1]=="")?"": "\n\nreadyState:" + a[1]) 
    		+ ((a[2]=="")?"": "\nstatus: " + a[2])
    		+ ((a[3]=="")?"": "\nstatusText: " + a[3]) 
    		+ ((a[4]=="")?"": "\n\nheaders:\n" + a[4]));
    	},
    	
    	/*----------------------------------------------------------
    	Restituisce il tipo di parametro ricevuto
    	0 -> indefinito
    	1 -> funzione
    	2 -> id oggetto che supporta innerHTML
    	3 -> id oggetto che supporta value
    	4 -> oggetto che supporta innerHTML
    	5 -> oggetto che supporta value
    	6 -> vettore
    	-----------------------------------------------------------*/
    	getTypeParameter:function(v)
    	{
    		if(typeof(v) == "undefined")
    		{
    			//alert("undefined");
    			return 0;
    		}
    		else if(typeof(v) == "function")
    		{
    			//alert("funzione");
    			return 1;
    		}
    		else if(typeof(v) == "string")
    		{
    			if(document.getElementById(v) != undefined)
    			{
    				if(document.getElementById(v).value != undefined)
    				{
    					//alert(" id value");
    					return 3;
    				}
    				else if(document.getElementById(v).innerHTML != undefined)
    				{
    					//alert("id innerHTML");
    					return 2;
    				}
    			}
    			else return 0;
    			
    
    		}
    		
    		else if(typeof(v) == "object")
    		{
    			if(v == null)
    			{
    				//alert("null");
    				return 0;
    			}
    			else
    			{
    				if(v.length != undefined)
    				{
    					//alert("vettore");
    					return 6;
    				}
    				else
    				{
    					if(v.value != undefined)
    					{
    						//alert(" oggetto value");
    						return 5;
    					}
    					else if(v.innerHTML != undefined)
    					{
    						//alert("oggetto innerHTML");
    						return 4;
    					}
    					
    				}
    			}
    		}
    		//indefinito o altro
    		return 0;
    		
    	},
    	
    	//-------------------------------------------------------------
    	// una volta recuperato l'xml con var tx = objHTTP.responseXML;
    	// e il testo con var t = objHTTP.responseText;
    	// stabilisco se ho ricevuo xml
    	//-------------------------------------------------------------
    	isXML:function(tx)
    	{
    		if(tx == null) return false;
    		if(tx.documentElement == null) return false;
    		return true;
    	}
    	
    	
    	
    }
    //========================== fine new ajax ==================================
    Pietro

  3. #3
    Utente di HTML.it L'avatar di Akito
    Registrato dal
    Nov 2005
    Messaggi
    101
    Grazie della risposta ma, dopo diverse prove, sono riuscito a risolvere il problema.
    Posto il codice se a qualcuno interessa.

    function createObject() {
    var tipo_richiesta;
    var browser = navigator.appName;
    if(browser == "Microsoft Internet Explorer") {
    tipo_richiesta = new ActiveXObject("Microsoft.XMLHTTP");
    }else{
    tipo_richiesta = new XMLHttpRequest();
    }
    return tipo_richiesta;
    }

    var http = createObject();

    function handleResponse(dest) {
    if(http.readyState < 4) {
    document.getElementById(dest).innerHTML = "Loading...stato="+http.readyState; // "status"
    }
    if(http.readyState == 4) {
    if(http.status == 200) {
    document.getElementById(dest).innerHTML = http.responseText; // "status"
    } else {
    document.getElementById(dest).innerHTML = http.status; // "status"
    }
    }
    }

    function sendGet(valore, dest) {
    http.open('GET', 'file.php?variabile='+valore, true);
    http.onreadystatechange = function() { handleResponse(dest); };
    http.send(null);
    }


    Ciao
    Akito

  4. #4
    Utente di HTML.it
    Registrato dal
    Jul 2006
    Messaggi
    14
    molto probabilmente sn io k nn ci ho capito 'na cippa ma lo script postato da pietro09 non viene eseguito da firefox 1.5 che anzi segnala degli errori nella sintassi riguardo a loadXMLDoc. .....

  5. #5
    Utente di HTML.it L'avatar di pietro09
    Registrato dal
    Jan 2002
    Messaggi
    10,116
    Originariamente inviato da xadhoom
    molto probabilmente sn io k nn ci ho capito 'na cippa ma lo script postato da pietro09 non viene eseguito da firefox 1.5 che anzi segnala degli errori nella sintassi riguardo a loadXMLDoc. .....
    :master: non so, ho copiato e incollato quel codice, provato con Firefox 1.5 e mi funziona
    Pietro

  6. #6
    Utente di HTML.it
    Registrato dal
    Jul 2006
    Messaggi
    14
    avrò sbagliato qalcosa io a implementarlo bho....ti farò sapere

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.