Ver Mensaje Individual
  #8 (permalink)  
Antiguo 27/05/2011, 01:37
Avatar de Panino5001
Panino5001
Me alejo de Omelas
 
Fecha de Ingreso: mayo-2004
Ubicación: -34.637167,-58.462984
Mensajes: 5.148
Antigüedad: 20 años
Puntos: 834
Respuesta: problemas con ajax: Acciones de href cargados con ajax

Lo que sucede es que hay que comprender bien cómo es el funcionamiento.

El primer error es querer colocar una referencia a un elemento que no existe. Eso no es posible: hay que esperar a que el elemento exista para poder referirse a él. Eso se logra con callbacks, que se invocan cuando AJAX entrega su respuesta (en eso se basa el ejemplo que te mostré) y eso también es justamente de lo que se trata el método success.

Otra cosa que podés hacer es cargar un html que tenga el javascript a ejecutar incluído (a eso se refería venkman en la respuesta que te dio en otro post, cuando mencionó evalscripts). No lo considero una buena práctica, pero si es lo que te interesa, te pongo un ejemplo:
enlaces.php
Código PHP:
<a id="a" href="#">decir hola</a> | <a id="b" href="#">decir chau</a> | <a id="c" href="#">hacer algo</a>
<
script type="text/javascript">
function 
setEvents(el,type,callback){
    
el[type]=callback;
    
el=null;//eliminamos referencias circulares
}
function 
asignar(){
    var 
callbacks=[function(){alert('hola');},function(){alert('chau');},function(){alert('¿qué hacemos?');}];
    var 
enlaces=[document.getElementById('a'),document.getElementById('b'),document.getElementById('c')];
    for(var 
i=0,o;o=enlaces[i];i++){
        
o.href='javascript:;';
        
setEvents(o,'onclick',callbacks[i]);
    }
}
asignar();
</script> 
documento principal:
Código PHP:
<!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>
<
meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<
title>Documento sin título</title>
<
script type="text/javascript">
String.prototype.tratarResponseText=function(){
    var 
pat=/<script[^>]*>([Ss]*?)</script[^>]*>/ig;
    var 
pat2=/bsrc=[^>s]+b/g;
    var 
elementos this.match(pat) || [];
    for(
i=0;i<elementos.length;i++) {
        var 
nuevoScript document.createElement('script');
        
nuevoScript.type 'text/javascript';
        var 
tienesrc=elementos[i].match(pat2) || [];
        if(
tienesrc.length){
            
nuevoScript.src=tienesrc[0].split("'").join('').split('"').join('').split('src=').join('').split(' ').join('');
        }else{
            var 
elemento elementos[i].replace(pat,'$1');
            
nuevoScript.text elemento;
        }
        
document.getElementsByTagName('body')[0].appendChild(nuevoScript);
    }
    return 
this.replace(pat,'');


function 
http(){
    if(
typeof window.XMLHttpRequest!='undefined'){
        return new 
XMLHttpRequest();    
    }else{
        try{
            return new 
ActiveXObject('Microsoft.XMLHTTP');
        }catch(
e){
            
alert('Su navegador no soporta AJAX');
            return 
false;
        }    
    }    
}
function 
request(url,callback,params){
    var 
H=new http();
    if(!
H)return;
    var 
p='';
    for(var 
i in params){
        
p+='&'+i+'='+encodeURIComponent(params[i]);    
    }
    
H.open('get',url+'?'+p+'&'+Math.random(),true);
    
H.onreadystatechange=function(){
        if(
H.readyState==4){
            
callback(H.responseText);
            
H.onreadystatechange=function(){}
            
H.abort();
            
H=null;
        }
    }
    
H.send(null);
}
onload=function(){
    
request('enlaces.php',function(r){ document.getElementById('rta').innerHTML=r;r.tratarResponseText();},{});
}
</script>

</head>

<body>
<div id="rta"></div>
</body>
</html>