Visualizzazione dei risultati da 1 a 6 su 6
  1. #1
    Utente di HTML.it
    Registrato dal
    Feb 2002
    Messaggi
    21

    [javascript dopo AJAX] come dare un refresh al DOM? eval()?

    Ciao,
    ho un problema che mi ha bloccato da 3 giorni a questa parte...sto per perdere ogni speranza.

    Ho una pagina index.html che ha nell'head uno script:

    <script src="rexite_fixed.js" type="text/javascript"></script>

    lo script contiene tra le altre cose una funzione che sostanzialmente recupera tutti i link della pagina e se ne trova alcuni con la classe=thumb_cat mi crea automaticamente lo stato del rollover.

    eccolo:

    Codice PHP:
    function zoom_over(id_el) {
        var 
    = $(id_el '_img');
        
    a.setAttribute("src""images/thumbs_scheda_cat/rollover/" id_el ".png"); 
    };

    function 
    zoom_out(id_el) {
        var 
    = $(id_el '_img');
        
    a.setAttribute("src""images/thumbs_scheda_cat/" id_el ".png"); 
    }

    function 
    ajax_rollover() {
     var 
    thumbs_cat =document.getElementsByTagName('a');
        for (var 
    i=0i<thumbs_cat.lengthi++) {
            if (
    thumbs_cat[i].className == 'thumb_cat') {
                
    alert('dentro');
                
    thumbs_cat[i].onmouseover = function() {
                    
    zoom_over(this.getAttribute('id'));
                }
                
    thumbs_cat[i].onmouseout = function() {
                    
    zoom_out(this.getAttribute('id'));
                }
            }
        }
        


    Nessun problema fin qui.
    Il punto è che la pagina index.html inizialmente non contiene nessun link con "class=thumb_cat". questi vengono inseriti nella pagina dopo una chiamata asincrona AJAX. Io utilizzo una libreria che si chiama LJAX, non penso che nessuno la conosca, ma non importa, io dico tramite LJAX di inserire del codice nella pagina e successivamente di richiamare la funzione ajax_rollover() che mi costruisca i rollover per il nuovo contenuto.
    Tutto funziona correttamente, il codice viene inserito nella pagina, la funzione viene correttamente chiamata (se inserisco un alert nella funzione ajax_rollover() lo vedo apparire dopo la chiamata AJAX) ma javascript continua a non trovare link con "class=thumb_cat" all'interno della pagina.

    E' come se dopo la chiamata AJAX ancora javascript continui a lavorare sul vecchio DOM e non su quello aggiornato da AJAX.

    Ho cercato negli archivi e ho trovato diversi thread in cui si suggeriva di usare eval()...ma come va usato nel mio caso?
    ho provato con:

    Codice PHP:
    function ajax_rollover() {
     eval(
    "var thumbs_cat =document.getElementsByTagName('a')");
        for (var 
    i=0i<thumbs_cat.lengthi++) {
            if (
    thumbs_cat[i].className == 'thumb_cat') {
                
    alert('dentro');
                
    thumbs_cat[i].onmouseover = function() {
                    
    zoom_over(this.getAttribute('id'));
                }
                
    thumbs_cat[i].onmouseout = function() {
                    
    zoom_out(this.getAttribute('id'));
                }
            }
        }

    ma nonostante non dia errori ancora non trova i nuovi link nel DOM.


    Che fare?
    Per favore aiuto, prometto eterna riconoscenza, denaro, fama, pubblicità gratis e quant'altro!

    Grazie,
    Augusto

  2. #2
    scrivi almeno cosa fai col responseText ... manca tutta la parte AJAX e tu hai un problema con quella, come aiutarti ?
    Formaldehyde a new Ajax PHP Zero Config Error Debugger

    WebReflection @WebReflection

  3. #3
    Utente di HTML.it
    Registrato dal
    Feb 2002
    Messaggi
    21
    in pratica in AJAX io sostituisco a:

    Codice PHP:
    <div id="product">

    </
    div
    questo:
    Codice PHP:
      <div id="product">
             
            <
    table border="0" align="center" cellpadding="0" cellspacing="0">
          <
    tr>
            <
    td>[url="olivia.lasso"][img]images/thumbs_scheda_cat/olivia.png[/img][/url]</td>
            <
    td>[url="#"][img]images/thumbs_scheda_cat/zanzibar.png[/img][/url]</td>
            <
    td>[url="#"][img]images/thumbs_scheda_cat/zanzi_swing.png[/img][/url]</td>
           </
    tr>
          <
    tr>
            <
    td>Olivia</td>
            <
    td>Zanzibar</td>
            <
    td>Zanzi Swing</td>
          </
    tr>
              <
    tr>
            <
    td>[url="#"][img]images/thumbs_scheda_cat/welcome.png[/img][/url]</td>
            <
    td>[url="#"][img]images/thumbs_scheda_cat/well.png[/img][/url]</td>
            <
    td>[url="#"][img]images/thumbs_scheda_cat/fritz.png[/img][/url]</td>
            </
    tr>
          <
    tr>
            <
    td>Welcome</td>
            <
    td>Well</td>
            <
    td>Fritz</td>
          </
    tr>
        </
    table>
      </
    div
    vuoi anche il codice dello script che uso?
    è questo:


    Codice PHP:
    Lasso 
    {
        
    SRC: (new String(document.location).match(/[^:]*:\/\/[^\/]*(\/[^\?|$|#]*)/)[1]),
        
    URL"LJAX.LassoApp",
        
    VERSION"0.0.1",
        
    REQUESTundefined,
        
    APPNAME"default",
        
    /*
        The data for a LJAX target is requested from within the client-side
        JavaScript by using the Lasso.includeTarget() function. This
        function accepts the following parameters:
        
        'targets' - The name or an array of names of the target(s) to retrieve.
        'options' - An object containing properties for the following:
            'args' - The argument string or an element such as a form, anchor or 
            other input element that will be used to create the argument string 
            which will be sent with the request
            
            'func' - If this optional function is provided, it will be called to
            handle the resulting data. This function will be passed the
            XMLHttpRequest object used for the request and the value of the 'param'
            parameter
            
            'param' - The parameter which is passed to the 'func' to handle the 
            resulting data. This is only utilized if 'func' is provided
            
            'afterFunc' - This optional function will be called, with the 
            XMLHttpRequest as it's only parameter after completing the include.
            
            'argsoverride' - Optional object containing the values that will be 
            substituted for the matching values found in the 'args' object. For 
            example, if argsoverride contained a property x with a value of y, and
            the args object was a form which contained an input field x, the value
            of y would be used regardless of the actual value of x in the form.
        */
        
    includeTarget: function(targetsoptions)
        {
            var 
    str '-src=' escape(this.SRC) + '&';
            if (
    typeof(targets) == 'string')
            {
                
    str += '-target=' escape(targets);
            }
            else
            {
                try
                {
                    for (var 
    0targets.length; ++i)
                    {
                        if (
    != 0)
                            
    str += '&';
                        
    str += '-target=' escape(targets[i]);
                    }
                }
                catch(
    e){ alert(e); }
            }
            if (
    options && options.args != undefined)
            {
                if (
    typeof(options.args) == 'string')
                {
                    
    str += '&' options.args;
                }
                else
                {
                    try
                    {
                        var 
    res this.encodeValuesFor(options.argsoptions.argsoverride);
                        if (
    res && res.length)
                            
    str += '&' res;
                    }catch(
    e){}
                }
            }
            return 
    this.fetchRequest(undefinedstr, (options && options.func != undefined) ? options.func :
                function(
    reqparam
                {                 
                    var 
    xml undefined;
                    if (
    req.responseXML)
                    {
                        var 
    elem req.responseXML.getElementsByTagName('ljax');
                        if (
    elem && elem.length 0)
                            
    xml elem[0];
                    }
                    if (
    xml == undefined || xml.nodeName != 'ljax')
                    {    
                        if (
    req.responseText && req.responseText.length 0)
                            
    document.write(req.responseText);
                        return;
                    }
                    for (var 
    idx 0idx xml.childNodes.length; ++idx)
                    {
                        var 
    thisXml xml.childNodes[idx];

                        
    // skip text nodes
                        
    if (thisXml.nodeType == 3) continue;

                        var 
    id thisXml.getAttribute('id');
                        if (
    thisXml && thisXml.nodeType == && id)
                        {
                            var 
    repNode document.getElementById(id);
                            if (
    repNode)
                            {
                                var 
    src '';
                                if (
    thisXml.innerHTML)
                                {
                                    
    src thisXml.innerHTML;
                                }
                                else if (
    thisXml.xml)
                                {
                                    for (var 
    innerIdx 0innerIdx thisXml.childNodes.length; ++innerIdx)
                                    {
                                        
    src += thisXml.childNodes[innerIdx].xml;
                                    }
                                }
                                else if (
    document.importNode)
                                {
                                    
    thisXml document.importNode(thisXmltrue);
                                    
    src thisXml.innerHTML;                            
                                }
                                
    repNode.innerHTML src;
                            }
                        }        
                    }
                }, 
    optionsoptions.param undefinedoptionsoptions.afterFunc undefined);
        },    
        
    onreadystatechange: function() // some implementations (Safari) send an Event as a param here
        
    {
            if (
    Lasso.REQUEST.readyState == 4)
            {
                if (
    Lasso.ljaxCallback != undefined)
                {
                    
    // this code is set up so that the ljaxCallbackPostFunc can re-issue another includeTarget call
                    // without the cleanup in here undoing any of it's work
                    // if this code is altered, make sure it is done safely with this in mind
                    
    Lasso.ljaxCallback(Lasso.REQUESTLasso.ljaxCallbackSecondParam);
                    
    Lasso.ljaxCallback undefined;
                    
    Lasso.ljaxCallbackSecondParam undefined;
                    
    Lasso.REQUEST.abort(); // have to call abort here or IE won't let you reuse the request
                    
    if (Lasso.ljaxCallbackPostFunc != undefined)
                    {
                        var 
    funcCopy Lasso.ljaxCallbackPostFunc;
                        
    Lasso.ljaxCallbackPostFunc undefined;
                        
    funcCopy(Lasso.REQUEST);
                    }
                }
            }
            else
            {
            
            }
        },
        
    fetchRequest: function(urlvaluecallbackcallbackSecondParampostFunc)
        {
            if (
    this.REQUEST == undefined)
            {
                if (
    window.XMLHttpRequest
                {
                    
    this.REQUEST = new XMLHttpRequest();
                }
                else if (
    window.ActiveXObject)
                {
                    
    this.REQUEST = new ActiveXObject("Microsoft.XMLHTTP");
                }
            }
            if (
    url == undefined)
            {
                
    url this.URL;
            }
            if (
    this.REQUEST)
            {
                
    this.ljaxCallback callback;
                
    this.ljaxCallbackSecondParam callbackSecondParam;
                
    this.ljaxCallbackPostFunc postFunc;
                
    this.REQUEST.onreadystatechange this.onreadystatechange;
                
    this.REQUEST.open("POST"urltrue);
                
    this.REQUEST.setRequestHeader('X-JLAX-VERSION'this.VERSION);
                
    this.REQUEST.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
                
    this.REQUEST.send(value);
                return 
    true;
            }
            return 
    false;
        },
        
    encodeValuesFor: function(inputoverride)
        {
            if (
    override == undefined)
                
    override = {};
            var 
    str '';
            var 
    nodeName input.nodeName.toLowerCase();
            if (
    nodeName == 'form')
            {
                for (var 
    0input.elements.length; ++i)
                {
                    if (
    != 0)
                        
    str += '&';
                    
    str += this.encodeValuesFor(input.elements[i], override);
                }
            }
            else if (
    nodeName == 'input' || nodeName == 'textarea')
            {
                
    str += escape(input.name) + '=' escape(override[input.name] != undefinedoverride[input.name] : input.value);
            }
            else if (
    nodeName == 'a')
            {
                var 
    idx input.href.indexOf('?');
                if (
    idx != -1)
                    
    str += input.href.substring(idx+1);
                
    // no input == else nothing to send
            
    }
            else if (
    nodeName == 'select')
            {
                if (
    override[input.name])
                {
                    
    str += escape(input.name) + '=' escape(override[input.name]);
                }
                else
                {
                    var 
    didOne false;
                    for (var 
    0input.options.length; ++i)
                    {
                        if (
    input.options[i].selected)
                        {
                            if (
    didOne)
                                
    str += '&';
                            
    didOne true;
                            
    str += input.name '=' input.options[i].value;
                        }
                    }
                }
            }    
            return 
    str;
        }

    grazie mille se riesci ad aiutarmi!

    Augusto

  4. #4
    ma da dove diamine esce questa libreria ? ... chi è che ha scritto un quintale di roba per altro discutibile per fare una banale chiamata asincrona ?

    guarda, lo consiglio raramente ... passa ad AHAH
    Formaldehyde a new Ajax PHP Zero Config Error Debugger

    WebReflection @WebReflection

  5. #5
    Utente di HTML.it L'avatar di pietro09
    Registrato dal
    Jan 2002
    Messaggi
    10,116
    Originariamente inviato da andr3a
    ma da dove diamine esce questa libreria ? ... chi è che ha scritto un quintale di roba per altro discutibile per fare una banale chiamata asincrona ?

    guarda, lo consiglio raramente ... passa ad AHAH

    Boh! il Mondo va in malora...
    Eh nohhh, ahah: anche io ho scritto qualcosa di meglio (e non sono certo bravo )

    Io consiglio caldamente l'amico Phishman di leggersi la guida scritta dal nostro Andrea, e a farsela lui la funzione. E una cosa è certa: farà senzaltro meglio di ahah :ignore:


    ps. ho provato ad fare qualche prova per rispondere al quesito proposto. Non con ajax (ho problemi di mal di testa) ma guardando alla sostanza del problema usando la funzione ajax_rollover()

    Basta, da un tasto, fare innerHTML in un div per verificare che il DOM è perfettamente aggiornato, sia con IE, sia con Firefox
    Pietro

  6. #6
    Originariamente inviato da pietro09
    Boh! il Mondo va in malora...
    Eh nohhh, ahah: anche io ho scritto qualcosa di meglio (e non sono certo bravo )
    non ho capito la tua risposta ... in merito a questa libreria:

    1 - utilizza un typeof "string" quando essa stessa istanzia una sua proprietà tramite new Sitrng (che ha typeof object) ... controllo del tipo discutibile

    2 - non usa il try catch per la giusta assegnazione cross browser dell'oggetto XMLHttpRequest mentre utilizza try catch per tutto il resto seppur non sia assolutamente necessario (try cath è per le eccezioni non gestibili, più che per sostituire if else ...)

    3 - escape è una funzione errata per inviare dati tramite ajax

    4 - i catch(eN){/* vuoti */} non servono a niente, try catch deve dare controllo, non fare ignorare parti problematiche di un metodo / funzione

    5 - controlli come if (req.responseText && req.responseText.length > 0) sono ridondanti, dato che una stringa vuota restituisce false in if tramite auto casting booleano

    6 - forzature tipo questa
    // have to call abort here or IE won't let you reuse the request
    non servono a niente


    ... altro ancora ... io non dico di imparare chissà cosa, ma almeno se scegliete una libreria sceglietela con:

    1 - supporto decente da parte di chi l'ha sviluppata
    2 - codice pensato e minimamente ottimizzato o lineare


    quindi frasi tipo
    Io consiglio caldamente l'amico Phishman di leggersi la guida scritta dal nostro Andrea, e a farsela lui la funzione.
    magari scritte senza malizia non sono, secondo me, troppo simpatiche ... dato che se ho scritto quello che ho scritto un motivo ci sarà, ed in parte l'ho elencato (piero non parlo necessariamente di te, mi metto anche nei suoi panni dopo aver letto le mie impressioni)



    Ricordo bene questa parte di 3D
    Io utilizzo una libreria che si chiama LJAX, non penso che nessuno la conosca, ma non importa
    hai perso una scommessa o usi una libreria che non ti da possibilità di avere la situazione sotto controllo per ordini superiori dettati dalla non eccessiva competenza in materia ?


    Insomma, colleghi, suvvia ... se dobbiamo scegliere una libreria che non conosciamo, scegliamone almeno una nota, sinonimo almeno di affidabilità dato che altri la stanno utilizzando senza problemi.


    Detto questo, mi scuso per non avere idea di quale sia il problema specifico ... per quel che mi riguarda ce ne sono diversi ma sicuramente sono io quello troppo ossessivo.


    Senza rancore, me
    Formaldehyde a new Ajax PHP Zero Config Error Debugger

    WebReflection @WebReflection

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.