Visualizzazione dei risultati da 1 a 9 su 9
  1. #1
    Utente di HTML.it L'avatar di henry78
    Registrato dal
    May 2001
    Messaggi
    1,264

    [Ajax] aggiungere anche il loading...

    ciao a tutti, ho questo script Ajax che funziona alla perfezione:

    <script>
    var XMLHTTP;

    function RichiestaAJAX1(data1,page)

    {
    //alert(data1);
    //alert(page);

    var url = "ajax.php?data=" + data1 + "&page=" + page;
    XMLHTTP1 = QualeBrowser(GestioneStato);
    XMLHTTP1.open("GET", url, true);
    XMLHTTP1.send(null);
    }

    function GestioneStato()
    {
    if (XMLHTTP1.readyState == 4)
    {
    var R = document.getElementById("data1");
    R.innerHTML = XMLHTTP1.responseText;
    }
    }
    </script>


    L'unico neo... non è previsto il "loading"...


    E' molto difficile fare in modo che mentre si caricano i contenuti del file esterno, compaia un gif animata con il loading???

    :master:

  2. #2
    Moderatore di JavaScript L'avatar di br1
    Registrato dal
    Jul 1999
    Messaggi
    19,998
    Il guaio per i poveri computers e' che sono gli uomini a comandarli.

    Attenzione ai titoli delle discussioni: (ri)leggete il regolamento
    Consultate la discussione in rilievo: script / discussioni utili
    Usate la funzione di Ricerca del Forum

  3. #3
    Utente di HTML.it L'avatar di henry78
    Registrato dal
    May 2001
    Messaggi
    1,264
    ma la gestione del loader... è possibile integrarlo alla mia funzione? oppure devo utilizzarne un altra?


  4. #4
    Utente di HTML.it L'avatar di pietro09
    Registrato dal
    Jan 2002
    Messaggi
    10,116
    Originariamente inviato da henry78
    ma la gestione del loader... è possibile integrarlo alla mia funzione? oppure devo utilizzarne un altra?

    Guarda questo esempio:
    codice:
    function Button1_onclick() 
    {
        $("img_attendere").style.display = "";
        $("Button1").disabled = true;
        
        var url = "?comando_ajax=1";    
        
        ajax(url, onload, null, onerror);
        function onload()
        {
           $("img_attendere").style.display = "none";
           $("Button1").disabled = false;
           
            var t = this.request.responseText;
            //var tx = this.request.responseXML;
            
            $("div1").innerHTML = t;
        }
    
        function onerror()
        {
            $("img_attendere").style.display = "none";
            $("Button1").disabled = false;
            this.defaultError();
        }
    }

    Dato che non è "internazionale", $ == document.getElementById


    Detto questo, Button1_onclick() è, per esempio, il metodo usato per far partire ajax.
    Lì ci faccio quello che voglio, ad esempio, disabilito il pulsante fino ad ottenere la risposta ($("Button1").disabled = true e mostro una gif animata di attesa ($("img_attendere").style.display = ""



    quando ottengo la risposta, nel metodo onload(), faccio esattamente il contrario, abilito il pulsante e nascondo l'immagine; stesso se ricevo un errore dal server.

    Per quanto riguarda se è meglio usare la "tua" funzione o un'altra, :master: , questo lo devi decidere tu.
    Per quanto mi riguarda, uso le mie funzioni, ma solo fino a che mi soddisfano. Se mi accorgo di qualche mio errore e non riesco a porci rimedio, le lascio e cerco di meglio.
    Pietro

  5. #5
    Utente di HTML.it L'avatar di henry78
    Registrato dal
    May 2001
    Messaggi
    1,264
    grazie molte Pietro,
    mi guardo con calma il tuo codice e cerco di adattare il mio.


  6. #6
    Utente di HTML.it L'avatar di pietro09
    Registrato dal
    Jan 2002
    Messaggi
    10,116
    nota:

    ajax(.... è una mia funzione, solo a titolo di esempio; prototype va più che bene.
    Pietro

  7. #7
    Utente di HTML.it L'avatar di henry78
    Registrato dal
    May 2001
    Messaggi
    1,264
    Pietro, mi posteresti il codice di una funzione Ajax come la usi tu in versione "completa"?


  8. #8
    Utente di HTML.it L'avatar di pietro09
    Registrato dal
    Jan 2002
    Messaggi
    10,116
    L'ho copiato da un mio file. Alcune funzioni non sono pertinenti ad ajax, perciò cancellale se non ti servono. Per spiegazioni sull'uso, disponibile, tempo permettendo.

    codice:
    /*--------------------------------------------------------------------------------------------------------------
    									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,
    					(l'oggetto può supportare innerHTML o value)
    					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
    -----------------------------------------------------------------------------------------------------------------*/
    function ajax(url, onload, parameters, onerror)
    {
    	parameters = (parameters == undefined)? "" : parameters;
    	//parameters = parameters.replace(/\+/g, "%2B");
    
    	//creazione oggetto per richiesta web
    	var objHTTP = getXMLHttp();
    	objHTTP.open("post", url, true);
    	objHTTP.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    	objHTTP.setRequestHeader('Content-length',parameters.length);
    	objHTTP.setRequestHeader('Connection', 'close');
    
    	objHTTP.onreadystatechange = function() 
    	{ 
    		if (objHTTP.readyState == 4) 
    		{
    			if (objHTTP.status == 200 || objHTTP.status == 0)
    			{
    				this.request = objHTTP;
    				if(onload)
    				{
                        //funzione di ritorno
                        if(getTypeParameter(onload) == 1) {onload.call(this);}
                        //identificativo tag che supporta innerHTML
                        else if(getTypeParameter(onload) == 2) {try {$(onload).innerHTML = this.request.responseText;} catch(e) {$(onload).innerHTML = e.message;}	}
                        //identificativo tag che supporta value
                        else if(getTypeParameter(onload) == 3) {try {$(onload).value = this.request.responseText;} catch(e) {$(onload).value = e.message;}	}
                        //oggetto tag che supporta innerHTML
                        else if(getTypeParameter(onload) == 4) {try {onload.innerHTML = this.request.responseText;} catch(e) {onload.innerHTML = e.message;}	}
                        //oggetto tag che supporta value
                        else if(getTypeParameter(onload) == 5) {try {onload.value = this.request.responseText;} catch(e) {onload.value = e.message;}	}
                        
                        
    				}
    				 
    				
    				
    			}											
    			//else {if(onerror && typeof(onerror) == "function") {onerror(defaultError); return;}else {defaultError(); return;}}
    			//else {if(onerror && typeof(onerror) == "function") {onerror.call(this); return;}else {defaultError(); return;}}
    			else
    			{
    			    this.defaultError = defaultError;
    			    if(onerror && typeof(onerror) == "function") {onerror.call(this); return;}else {defaultError(); return;}
    			}
    		}
    	};
    
        objHTTP.send(parameters);
        
    
        function getXMLHttp() 
        {
    	    var xmlhttp = null;
        	
    	    if(window.XMLHttpRequest) 
    	    {
    		    xmlhttp = new XMLHttpRequest(); // Gecko (Firefox, Moz), KHTML (Konqueror, Safari), Opera, Internet Explorer 7
    	    } 
    	    else if(window.ActiveXObject) 
    	    {
    		    try
    		    {
    			    xmlhttp = new ActiveXObject("MSXML2.XMLHTTP"); // Internet Explorer 6 
    		    } 
    		    catch(e) 
    		    {
    			    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); // Internet Explorer 4,5 
    		    }
    		    } 
    	    else 
    	    {
    		    xmlhttp = null;
    	    }
    	    return xmlhttp;
        };
    
    	function defaultError()
    	{
    		alert("ERRORE NELLA TRASMISSIONE DATI!");
    	};
    }
    
    //al posto di mettere document.getElementById("div1"), mettere $("div1")
    //da prototype.js
    function $() {
      var elements = new Array();
    
      for (var i = 0; i < arguments.length; i++) {
        var element = arguments[i];
        if (typeof element == 'string')
          element = document.getElementById(element);
    
        if (arguments.length == 1)
          return element;
    
        elements.push(element);
      }
    
      return elements;
    }
    
    /*----------------------------------------------------------
    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
    -----------------------------------------------------------*/
    function getTypeParameter(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
    //-------------------------------------------------------------
    function isXML(tx)
    {
    	if(tx == null) return false;
    	if(tx.documentElement == null) return false;
    	return true;
    }
    
    
    
    
    //-----------------------------------------------------
    //valuta il codice javascript e restituisce la stringa
    //senza codice
    //-----------------------------------------------------
    function execJS(t)
    {
        var p1 = 0, p2 = 0, p3 = 0, p4 = 0;
        p1 = t.indexOf("<" + "script", 0);
        if(p1 == -1) return t;
        
        p2 = t.indexOf(">", p1 + 7) + 1;
        p3 = t.indexOf("<" + "/script>", p2);
        p4 = p3 + 9;
        
        var c = t.substring(p2, p3);
        var s = document.createElement("script");
        s.type = "text/javascript";
        s.text = c;
        document.getElementsByTagName("head")[0].appendChild(s);
        
        t = t.substring(0, p1) + t.substr(p4);
        return execJS(t);
    
    }
    
    //-----------------------------------------------------------------
    //crea la stringa dei parametri da utilizzare con ajax
    //-----------------------------------------------------------------
    function crea_parametri(form)
    {
        if(typeof(form) == "undefined")
            return;
        else if(typeof(form) == "string")
        {
            var f = document.getElementById(form);
            if(!f) return;
        }
        else if(typeof(form) == "object")
            var f = form;
        
        
        var elements = f.elements;
        if(!elements) return;
        var n = elements.length;
        var s = [];
        for(var i = 0; i < n; i++)
        {
            var element = elements[i];
            var name = element.name;
            if(name != "")
            {
                var type = element.type;
                var value = encodeURIComponent(element.value);
                if(type == "text" || type == "file" || type == "password" )
                {
                    s.push(name + "=" + value);
                }
                
                else if(type == "hidden")
                {
                    //non considero gli elementi riservati quali:
                    //__EVENTTARGET, __EVENTARGUMENT, __VIEWSTATE, __EVENTVALIDATION
                    if(name.indexOf("__", 0) == -1) s.push(name + "=" + value);
                }
                
                else if(type == "checkbox" || type == "radio" )
                {
                    if(element.checked)
                    {
                        s.push(name + "=" + value);
                    }            
                }
                else if(type == "textarea")
                {
                    s.push(name + "=" + value);
                }
                
                else if(type == "select-one" || type == "select-multiple")
                {
                    var c = options_value_selezionati_join(element) + "";
                    if(c != "") s.push(name + "=" + c);
                }
                
            }
            
        }
        s = s.join("&");
        return s;
    
    
        //------------------------------------------------------------
        //restituisce gli elementi value selezionati da una lista
        //separati da virgola
        //------------------------------------------------------------
        function options_value_selezionati_join(lista)
        {
    	    var s = "";
    	    for(var i = 0; i < lista.options.length; i++)
    	    {
    		    if(lista.options[i].selected) s += "," + lista.options[i].value;
    	    }
    	    return s.substr(1);
        }
    
    
    
    
    }
    
    //-------------------------------------------------------------------------------------
    //restituisce i parametri riservati da asp.net
    //v è il controllo o l'id del controllo che fa il submit tramite ajax
    //-------------------------------------------------------------------------------------
    function parametri_riservati(v)
    {
        if (typeof v == 'string') v = document.getElementById(v);
        
        var result = "";
        
        if(self.$("__EVENTTARGET")) result+= "&" + $("__EVENTTARGET").name + "=" + v.id;
        if(self.$("__EVENTARGUMENT")) result+= "&" + $("__EVENTARGUMENT").name + "=" + "";
        if(self.$("__VIEWSTATE")) result+= "&" + $("__VIEWSTATE").name + "=" + encodeURIComponent($("__VIEWSTATE").value);
        if(self.$("__EVENTVALIDATION")) result+= "&" + $("__EVENTVALIDATION").name + "=" + encodeURIComponent($("__EVENTVALIDATION").value);
        
        if(result.indexOf("&", 0) == 0) result = result.substr(1);
        return result;   
    }
    
    /*-----------------------------------------------------------------------
    nella pagina c'è un iframe nascosto:
    <iframe id="iframe_tmp" name="iframe_tmp" style="display:none;"></iframe>
    recupero il document da una stringa, per esempio:
    var pagina = "<html><body><input type='text' id='text1' value='Pinco Pallino'  /></body></html>";
    var d = getDocumentFromHtml(pagina);
    alert(d.getElementById("text1").value);
    ------------------------------------------------------------------------*/
    function getDocumentFromHtml(pagina)
    {
        var w = window.open("", document.getElementById("iframe_tmp").name);
        var d = w.document;
        d.open();
        d.writeln(pagina);
        d.close();
        return d;
    }
    Pietro

  9. #9
    Utente di HTML.it L'avatar di henry78
    Registrato dal
    May 2001
    Messaggi
    1,264
    Grazie 1000!

    sei davvero gentilissimo!


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.