Foros del Web » Programando para Internet » Javascript » Frameworks JS »

Alguien me ayuda a mejorar esto

Estas en el tema de Alguien me ayuda a mejorar esto en el foro de Frameworks JS en Foros del Web. Hola, esta es una clase que estoy armando yo mismo, y la verdad que venia todo bien pero no me esta cargando la pagina solo ...
  #1 (permalink)  
Antiguo 08/08/2008, 06:53
Avatar de korg1988  
Fecha de Ingreso: junio-2006
Ubicación: Santa Fe, Argentina
Mensajes: 825
Antigüedad: 17 años, 9 meses
Puntos: 19
De acuerdo Me tira el cartel "Cargando" pero no me carga la pagina!

Hola, esta es una clase que estoy armando yo mismo, y la verdad que venia todo bien pero no me esta cargando la pagina solo me muestra el mensaje de cargando, el problema esta en el onreadystatechange creo
Código PHP:
<html>
<
head>
<
script>
function 
Ajax()
{
    
//--------------------------
    // Variables
    //--------------------------
    
this.handler false//Objeto

    //--------------------------
    // Funciones
    //--------------------------
    
this.conectar = function()
    {
        if(
navigator.appName == "Microsoft Internet Explorer") {
            try {
                
this.handler = new ActiveXObject('Msxml2.XMLHTTP');
            } catch(
e) {
                try {
                    
this.handler = new ActiveXObject('Microsoft.XMLHTTP');
                } catch(
e) {}
            }
        } else {
            
this.handler = new XMLHttpRequest();
        }
    }
    
    
this.estados = function()
    {
        if(
this.handler.readyState == 1) {
            
document.getElementById('estado').innerHTML "Cargando...";
        } else if (
this.handler.readyState == 4) {
            
document.getElementById('estado').innerHTML "Finalizado...";
            
document.getElementById('carga').innerHTML this.handler.responseText;
        }
    }
    
    
this.enviar = function(urlmetodovalores)
    {
        
this.handler.open(metodourltrue);
        
this.handler.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        
this.handler.onreadystatechange this.estados();
        
        if(
metodo.toUpperCase() == 'POST') {
            
this.handler.send(valores);
        } else {
            
this.handler.send(null);
        }
    }
}

window.onload = function()
{
    
pagina = new Ajax();
    
pagina.conectar();
    
pagina.enviar('prueba.php''GET');
}
</script>
</head>

<body>
<div id="estado">En espera</div>
<div id="carga">Vacio</div>
</body>
</html> 
Salutes
  #2 (permalink)  
Antiguo 08/08/2008, 09:06
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 11 meses
Puntos: 2135
Respuesta: Me tira el cartel "Cargando" pero no me carga la pagina!

Asi es, recuerda que si lo que quieres es copiar la referencia a una función no es lo correcto hacerlo asi:
Código:
this.handler.onreadystatechange = this.estados();
Debe de ser así:
Código:
this.handler.onreadystatechange = this.estados;
  #3 (permalink)  
Antiguo 08/08/2008, 09:22
Avatar de Panino5001
Me alejo de Omelas
 
Fecha de Ingreso: mayo-2004
Ubicación: -34.637167,-58.462984
Mensajes: 5.148
Antigüedad: 19 años, 11 meses
Puntos: 834
Respuesta: Me tira el cartel "Cargando" pero no me carga la pagina!

Tenés problemas con el llamado y los ámbitos (se genera una closure y no la estás resolviendo). Probá así:
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=iso-8859-1" />
<
title>test closures</title>
<
html>
<
head>
<
script>
function 
Ajax()
{
    
//--------------------------
    // Variables
    //--------------------------
    
this.handler false//Objeto

    //--------------------------
    // Funciones
    //--------------------------
    
this.conectar = function()
    {
        if(
navigator.appName == "Microsoft Internet Explorer") {
            try {
                
this.handler = new ActiveXObject('Msxml2.XMLHTTP');
            } catch(
e) {
                try {
                    
this.handler = new ActiveXObject('Microsoft.XMLHTTP');
                } catch(
e) {}
            }
        } else {
            
this.handler = new XMLHttpRequest();
        }
    }
    var 
_this=this;//con esto solucionás el tema del scope
    
this.estados = function()
    {
    
        if(
_this.handler.readyState == 1) {
            
document.getElementById('estado').innerHTML "Cargando...";
        } else if (
_this.handler.readyState == 4) {
            
document.getElementById('estado').innerHTML "Finalizado...";
            
document.getElementById('carga').innerHTML _this.handler.responseText;
        }
    }
    
    
this.enviar = function(urlmetodovalores)
    {
        
this.handler.open(metodourltrue);
        
this.handler.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        
this.handler.onreadystatechange this.estados;
        
        if(
metodo.toUpperCase() == 'POST') {
            
this.handler.send(valores);
        } else {
            
this.handler.send(null);
        }
    }
}

window.onload = function()
{
    
pagina = new Ajax();
    
pagina.conectar();
    
pagina.enviar('prueba.php''GET');
}
</script>
</head>

<body>
<div id="estado">En espera</div>
<div id="carga">Vacio</div>
</body>
</html> 
Edito: ups, se me adelantó GatorV, pero bueno, sin resolver la closure tampoco te habría funcionado ;)

Última edición por Panino5001; 08/08/2008 a las 09:27
  #4 (permalink)  
Antiguo 08/08/2008, 11:51
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 11 meses
Puntos: 2135
Respuesta: Me tira el cartel "Cargando" pero no me carga la pagina!

jeje por eso prefiero bind de Prototype
  #5 (permalink)  
Antiguo 08/08/2008, 14:10
Avatar de Panino5001
Me alejo de Omelas
 
Fecha de Ingreso: mayo-2004
Ubicación: -34.637167,-58.462984
Mensajes: 5.148
Antigüedad: 19 años, 11 meses
Puntos: 834
Respuesta: Me tira el cartel "Cargando" pero no me carga la pagina!

En realidad, siguiendo las enseñanzas de nuestro amigo maborak, hay una manera más elegante de resolver las closures, con la ventaja adicional de que puede usarse más tarde para eliminar algún patrón de memory leak en explorer:
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=iso-8859-1" />
<
title>test closures</title>
<
html>
<
head>
<
script>
//credits:http://laurens.vd.oever.nl/
Function.prototype.closure = function(obj)
{
  
// Init object storage.
  
if (!window.__objs)
  {
    
window.__objs = [];
    
window.__funs = [];
  }

  
// For symmetry and clarity.
  
var fun this;

  
// Make sure the object has an id and is stored in the object store.
  
var objId obj.__objId;
  if (!
objId)
    
__objs[objId obj.__objId __objs.length] = obj;

  
// Make sure the function has an id and is stored in the function store.
  
var funId fun.__funId;
  if (!
funId)
    
__funs[funId fun.__funId __funs.length] = fun;

  
// Init closure storage.
  
if (!obj.__closures)
    
obj.__closures = [];

  
// See if we previously created a closure for this object/function pair.
  
var closure obj.__closures[funId];
  if (
closure)
    return 
closure;

  
// Clear references to keep them out of the closure scope.
  
obj null;
  
fun null;

  
// Create the closure, store in cache and return result.
  
return __objs[objId].__closures[funId] = function ()
  {
    return 
__funs[funId].apply(__objs[objId], arguments);
  };
};
function 
Ajax()
{
    
//--------------------------
    // Variables
    //--------------------------
    
this.handler false//Objeto

    //--------------------------
    // Funciones
    //--------------------------
    
this.conectar = function()
    {
        if(
navigator.appName == "Microsoft Internet Explorer") {
            try {
                
this.handler = new ActiveXObject('Msxml2.XMLHTTP');
            } catch(
e) {
                try {
                    
this.handler = new ActiveXObject('Microsoft.XMLHTTP');
                } catch(
e) {}
            }
        } else {
            
this.handler = new XMLHttpRequest();
        }
    }
    
this.estados = function()
    {
    
        if(
this.handler.readyState == 1) {
           
document.getElementById('estado').innerHTML "Cargando...";
        } else if (
this.handler.readyState == 4) {
            
document.getElementById('estado').innerHTML "Finalizado...";
            
document.getElementById('carga').innerHTML this.handler.responseText;
            
        }
        
    }
    
    
this.enviar = function(urlmetodovalores)
    {
        
this.handler.open(metodourltrue);
        
this.handler.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        
this.handler.onreadystatechange this.estados.closure(this);
        
        if(
metodo.toUpperCase() == 'POST') {
            
this.handler.send(valores);
        } else {
            
this.handler.send(null);
        }
    }
}

window.onload = function()
{
    
pagina = new Ajax();
    
pagina.conectar();
    
pagina.enviar('prueba.php''GET');
}
</script>
</head>

<body>
<div id="estado">En espera</div>
<div id="carga">Vacio</div>
</body>
</html> 
  #6 (permalink)  
Antiguo 08/08/2008, 14:24
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 11 meses
Puntos: 2135
Respuesta: Me tira el cartel "Cargando" pero no me carga la pagina!

Es básicamente lo que hace prototype, pero a un ámbito más general, creo es una buena solución.
  #7 (permalink)  
Antiguo 08/08/2008, 14:45
Avatar de MaBoRaK  
Fecha de Ingreso: abril-2003
Ubicación: La Paz - Bolivia
Mensajes: 2.003
Antigüedad: 21 años
Puntos: 35
Respuesta: Me tira el cartel "Cargando" pero no me carga la pagina!

loading...............

Bueno aplicando esto tambien se podría encapsular TODOS los metodos de una clase.
Código PHP:
          var argumentsToArray=function(a){
                 var 
args=[];
                for(var 
i=0;i<a.length;i++){args.push(a[i]);};
                 return 
args;
         };


        
Object.prototype.isObjectStrict = function()
         {
               return (
this.appendChild)?false:true;
         };
         
/**
        * es| Expandir una Clase dentro de sus objetos literales
        * @param {Object}
        */
        
Object.prototype.expand=function(Class,recursive)
        {
                Class=Class || 
this;
                for(var 
i in this)
                {
                        if(
this.propertyIsEnumerable(i) && (typeof this[i]==="function" || (recursive===true && typeof this[i]==="object" && this[i].isObjectStrict())))
                        {
                                try{
                                        if(
typeof this[i]==="function")
                                        {
                                                
//kkk.push(this[i]);
                                                
this[i]=this[i].extend(Class);
                                        }
                                        else
                                        {
                                                
this[i]=this[i].expand(Class,recursive);
                                        }
                                }
                                catch(
e){
                                        
this[i]=this[i];
                                }
                        }
                        else
                        {
                                
//alert(i);
                        
}
                }
                return 
this;
        };
        Function.
prototype.isObject     false;
        Function.
prototype.isArray      false;
        
/**
        * es| Expandir función en una Clase
        * @param {Funcion}
        */
        
Function.prototype.extend=function(Class)
        {
                try{
                        var 
oThis=this;
                        var 
args=argumentsToArray(arguments);
                        
args.splice(0,1);
                        return function()
                        {
                                return 
oThis.apply(Class,argumentsToArray(arguments).concat(args));
                        };
                }
                catch(
e){
                        return 
this;
                }
        };
        
/**
        * es| Añadir argumentos a una función
        * @param {Function}
        */
        
Function.prototype.args=function()
        {
                var 
oThis=this;
                var 
args=argumentsToArray(arguments);
                return function()
                {
                        return 
oThis.apply(oThis,argumentsToArray(arguments).concat(args));
                };
        }; 
Código:
function Ajax()
{
    //--------------------------
    // Variables
    //--------------------------
    this.handler = false; //Objeto

    //--------------------------
    // Funciones
    //--------------------------
    this.conectar = function()
    {
    }
    this.estados = function()
    {
    }
    
    this.enviar = function(url, metodo, valores)
    {
        this.handler.open(metodo, url, true);
        this.handler.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        this.handler.onreadystatechange = this.estados;
        
        if(metodo.toUpperCase() == 'POST') {
            this.handler.send(valores);
        } else {
            this.handler.send(null);
        }
    }
    this.expand(this);
    return this;
}

window.onload = function()
{
    pagina = new Ajax();
    pagina.conectar();
    pagina.enviar('prueba.php', 'GET');
}
</script>
</head>

<body>
<div id="estado">En espera</div>
<div id="carga">Vacio</div>
</body>
</html>
De esta forma como dije, todos los métodos de la clase ya vienen ENCERRADAS.

TODO EN UNO

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=iso-8859-1" />
<
title>test closures</title>
<
html>
<
head>
<
script>
          var 
argumentsToArray=function(a){
                 var 
args=[];
                for(var 
i=0;i<a.length;i++){args.push(a[i]);};
                 return 
args;
         };


        
Object.prototype.isObjectStrict = function()
         {
               return (
this.appendChild)?false:true;
         };
         
/**
        * es| Expandir una Clase dentro de sus objetos literales
        * @param {Object}
        */
        
Object.prototype.expand=function(Class,recursive)
        {
                Class=Class || 
this;
                for(var 
i in this)
                {
                        if(
this.propertyIsEnumerable(i) && (typeof this[i]==="function" || (recursive===true && typeof this[i]==="object" && this[i].isObjectStrict())))
                        {
                                try{
                                        if(
typeof this[i]==="function")
                                        {
                                                
//kkk.push(this[i]);
                                                
this[i]=this[i].extend(Class);
                                        }
                                        else
                                        {
                                                
this[i]=this[i].expand(Class,recursive);
                                        }
                                }
                                catch(
e){
                                        
this[i]=this[i];
                                }
                        }
                        else
                        {
                                
//alert(i);
                        
}
                }
                return 
this;
        };
        Function.
prototype.isObject     false;
        Function.
prototype.isArray      false;
        
/**
        * es| Expandir función en una Clase
        * @param {Funcion}
        */
        
Function.prototype.extend=function(Class)
        {
                try{
                        var 
oThis=this;
                        var 
args=argumentsToArray(arguments);
                        
args.splice(0,1);
                        return function()
                        {
                                return 
oThis.apply(Class,argumentsToArray(arguments).concat(args));
                        };
                }
                catch(
e){
                        return 
this;
                }
        };
        
/**
        * es| Añadir argumentos a una función
        * @param {Function}
        */
        
Function.prototype.args=function()
        {
                var 
oThis=this;
                var 
args=argumentsToArray(arguments);
                return function()
                {
                        return 
oThis.apply(oThis,argumentsToArray(arguments).concat(args));
                };
        };
function 
Ajax()
{
    
//--------------------------
    // Variables
    //--------------------------
    
this.handler false//Objeto

    //--------------------------
    // Funciones
    //--------------------------
    
this.conectar = function()
    {
        if(
navigator.appName == "Microsoft Internet Explorer") {
            try {
                
this.handler = new ActiveXObject('Msxml2.XMLHTTP');
            } catch(
e) {
                try {
                    
this.handler = new ActiveXObject('Microsoft.XMLHTTP');
                } catch(
e) {}
            }
        } else {
            
this.handler = new XMLHttpRequest();
        }
    }
    
this.estados = function()
    {
    
        if(
this.handler.readyState == 1) {
           
document.getElementById('estado').innerHTML "Cargando...";
        } else if (
this.handler.readyState == 4) {
            
document.getElementById('estado').innerHTML "Finalizado...";
            
document.getElementById('carga').innerHTML this.handler.responseText;
            
        }
        
    }
    
    
this.enviar = function(urlmetodovalores)
    {
        
this.handler.open(metodourltrue);
        
this.handler.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        
this.handler.onreadystatechange this.estados;
        
        if(
metodo.toUpperCase() == 'POST') {
            
this.handler.send(valores);
        } else {
            
this.handler.send(null);
        }
    };
    
this.expand(this);
    return 
this;
}

window.onload = function()
{
    
pagina = new Ajax();
    
pagina.conectar();
    
pagina.enviar('prueba.php''GET');
}
</script>
</head>

<body>
<div id="estado">En espera</div>
<div id="carga">Vacio</div>
</body>
</html> 
connection closed.
__________________

Maborak Technologies
  #8 (permalink)  
Antiguo 08/08/2008, 15:04
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 11 meses
Puntos: 2135
Respuesta: Me tira el cartel "Cargando" pero no me carga la pagina!

jejeje perfecto, o ya mejor usar Ajax.Request de prototype directamente
  #9 (permalink)  
Antiguo 08/08/2008, 15:56
Avatar de Panino5001
Me alejo de Omelas
 
Fecha de Ingreso: mayo-2004
Ubicación: -34.637167,-58.462984
Mensajes: 5.148
Antigüedad: 19 años, 11 meses
Puntos: 834
Respuesta: Me tira el cartel "Cargando" pero no me carga la pagina!

Ja, ja, me tomará un tiempito ver esto.
Hay un truco más sencillo para convertir arguments en array:
Código PHP:
args = Array.prototype.slice.call(arguments); 
o
Código PHP:
<script>
function 
test(a,b,c){
args = [].slice.call(arguments,0);
alert(args.constructor);
}
test(1,2,3);
</script> 

Última edición por Panino5001; 08/08/2008 a las 22:34
  #10 (permalink)  
Antiguo 09/08/2008, 20:55
Avatar de korg1988  
Fecha de Ingreso: junio-2006
Ubicación: Santa Fe, Argentina
Mensajes: 825
Antigüedad: 17 años, 9 meses
Puntos: 19
Respuesta: Me tira el cartel "Cargando" pero no me carga la pagina!

muchas gracias por todas sus respuestas! pero la verdad es que no entendi nada! jaja

Panino5001
El tema del Scope(que no se lo que es)
Me decis que se soluciona haciendo esto
var _this = this;

_this.handler.bla_bla!

pero o sea si vamos al caso..... no es lo mismo eso que poner
this.handler.bla_bla???
porque _this tiene adentro el valor de this...

ASi que no entiendo, y luego cuando hablan de prototype y me dan todos esos codigos no encuentro su relacion con mi codigo!

Gracias a todos! si alguien me podria explicar un poquito mas! se lo agradeceria mucho
  #11 (permalink)  
Antiguo 09/08/2008, 23:01
Avatar de Panino5001
Me alejo de Omelas
 
Fecha de Ingreso: mayo-2004
Ubicación: -34.637167,-58.462984
Mensajes: 5.148
Antigüedad: 19 años, 11 meses
Puntos: 834
Respuesta: Me tira el cartel "Cargando" pero no me carga la pagina!

Lo que sucede es que en ese contexto se crea una situación en donde this no es una referencia al objeto que necesitás referenciar, sino a otro.
Un ejemplo donde quizá se vea más claro es este:
Código PHP:
<script>
function 
test(){
        
this.algo='hola';
    
this.test1=function(){
        
alert(this.constructor);
    }
    
this.test2=function(){
        (function(){
alert(this.constructor);})();
    }
}
t=new test;
t.test1();
t.test2();
</script> 
Como ves, los resultados son diferentes, ya que this, en ese contexto, apunta a diferentes objetos (En explorer el segundo alert muestra undefinded y en los navegadores standard muestra object, pero el primer alert en todos los casos refiere a la función constructora del objeto test)
En cambio, si se referencia a this de manera indirecta, ya funcionará como se necesita:
Código PHP:
<script>
function 
test(){
    
this.algo='hola';
    
this.test1=function(){
        
alert(this.constructor);
    }
    
_this=this;
    
this.test2=function(){
        (function(){
alert(_this.constructor);})();
    }
}
t=new test;
t.test1();
t.test2();
</script> 
En los ejemplos usé constructor, pero el resultado sería el mismo con la propiedad algo.
  #12 (permalink)  
Antiguo 10/08/2008, 18:36
Avatar de korg1988  
Fecha de Ingreso: junio-2006
Ubicación: Santa Fe, Argentina
Mensajes: 825
Antigüedad: 17 años, 9 meses
Puntos: 19
Respuesta: Me tira el cartel "Cargando" pero no me carga la pagina!

ahhhh creo que ya entendi! ;) entonces directamente para prevenir errores no me conviene crear una variable que contenga a this dentro? y usar esa variable? ya que si hubiece hecho eso no me hubiece ocurrido eso!
  #13 (permalink)  
Antiguo 10/08/2008, 21:23
Avatar de korg1988  
Fecha de Ingreso: junio-2006
Ubicación: Santa Fe, Argentina
Mensajes: 825
Antigüedad: 17 años, 9 meses
Puntos: 19
De acuerdo Respuesta: Me tira el cartel "Cargando" pero no me carga la pagina!

bueno probe como lo dije antes y funciono perfecto, quiza es una buena forma de mantener los diferentes "niveles" que tiene el objeto parece ser! ya que pense que this! se referia a tooda la "class"(supuestamente si lo llamamos asi)" , pero se ve que no tiene alcanze dentro de todos los niveles, igualmente no me queda muy claro del todo!

el codigo me quedo asi
Código PHP:
<html>
<
head>
<
script>
function 
Ajax()
{
    
//--------------------------
    // Variables
    //--------------------------
    
_this this;
    
_this.handler false//Objeto
    //--------------------------
    // Funciones
    //--------------------------
    
_this.conectar = function()
    {
        if(
navigator.appName == "Microsoft Internet Explorer") {
            try {
                
_this.handler = new ActiveXObject('Msxml2.XMLHTTP');
            } catch(
e) {
                try {
                    
_this.handler = new ActiveXObject('Microsoft.XMLHTTP');
                } catch(
e) {}
            }
        } else {
            
_this.handler = new XMLHttpRequest();
        }
    }
    
    
_this.estados = function()
    {
        if(
_this.handler.readyState == 1) {
            
document.getElementById('estado').innerHTML "Cargando...";
        } else if (
_this.handler.readyState == 4) {
            
document.getElementById('estado').innerHTML "Finalizado...";
            
document.getElementById('carga').innerHTML _this.handler.responseText;
        }
    }
    
    
_this.enviar = function(urlmetodoparametros)
    {
        
_this.handler.open(metodourltrue);
        
_this.handler.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        
_this.handler.onreadystatechange _this.estados;
        
        if(
metodo.toUpperCase() == 'POST') {
            
_this.handler.send(parametros);
        } else {
            
_this.handler.send(null);
        }
    }
}

window.onload = function()
{
    
pagina = new Ajax();
    
pagina.conectar();
    
pagina.enviar('prueba.php''GET');
//    cargar("prueba.php", "GET", null, "carga", "estado");
}
</script>
</head>

<body>
<div id="estado">En espera</div>
<div id="carga">Vacio</div>
</body>
</html> 
  #14 (permalink)  
Antiguo 11/08/2008, 09:22
Avatar de korg1988  
Fecha de Ingreso: junio-2006
Ubicación: Santa Fe, Argentina
Mensajes: 825
Antigüedad: 17 años, 9 meses
Puntos: 19
De acuerdo Alguien me ayuda a mejorar esto

HOla bueno abri este post poruqe el que tenia abierto antes se estaba haciendo medio largo y no daba para seguir preguntando! ya uqe habia solucionado mi problema!
el post es http://www.forosdelweb.com/f77/tira-...3/#post2525908

bueno, el codigo es el siguiente
No es mas que un simple Loader Ajax! pero bueno, quize armar mi propia class y hace poco que empece a crear mis propios objetos con javascript

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>

<
script>
function 
Ajax()
{
/*
*    Variables
*/
    
_this            =    this;
    
_this.Handler    =    false//Objeto
/*
* ESTADOS
*/
    
_this.Estados    =    new Object();
    
_this.Estados.Tipos =     new Array();
    
_this.Estados.Tipos['CARGANDO']    =    new Object();
    
_this.Estados.Tipos['COMPLETO']    =    new Object();
    
_this.Estados.Tipos['DESTINO']    =    new Object();
    
    
_this.Estados.Tipos['CARGANDO'].Value    =    1;
    
_this.Estados.Tipos['CARGANDO'].Msj        =    '';
    
_this.Estados.Tipos['CARGANDO'].ObjId    =    '';
    
    
_this.Estados.Tipos['COMPLETO'].Value    =    4;
    
_this.Estados.Tipos['COMPLETO'].Msj        =    '';
    
_this.Estados.Tipos['COMPLETO'].ObjId    =    '';
    
    
_this.Estados.Tipos['DESTINO'].ObjId    =    '';
    
/*
*    CONECTAR 'establece el objeto XMLHttpRequest'
*/
    
_this.Conectar = function()
    {
        if(
navigator.appName == "Microsoft Internet Explorer") {
            try {
                
_this.Handler = new ActiveXObject('Msxml2.XMLHTTP');
            } catch(
e) {
                try {
                    
_this.Handler = new ActiveXObject('Microsoft.XMLHTTP');
                } catch(
e) {}
            }
        } else {
            
_this.Handler = new XMLHttpRequest();
        }
    }
/*
*    CAMBIOS DE ESTADO 'acciones para onreadystatechange'
*/    
    
_this.Estados.Change = function()
    {
        if(
_this.Handler.readyState == _this.Estados.Tipos['CARGANDO'].Value) {
            
_this.Estados.Show(_this.Estados.Tipos['CARGANDO'].ObjId_this.Estados.Tipos['CARGANDO'].Msj);
        } else if(
_this.Handler.readyState == _this.Estados.Tipos['COMPLETO'].Value) {
            
_this.Estados.Show(_this.Estados.Tipos['COMPLETO'].ObjId_this.Estados.Tipos['COMPLETO'].Msj);
            
_this.Estados.Show(_this.Estados.Tipos['DESTINO'].ObjId_this.Handler.responseText);
        }
    }
/*
*    ENVIAR 'funcion estandar para envio de datos'
*/
    
_this.Enviar = function(urlmetodoparametros)
    {
        if(
_this.Handler == false) { _this.Conectar(); }    //Si no existe la conexion entonces la crea por unica vez
        
_this.Handler.open(metodourltrue);
        
_this.Handler.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        
_this.Handler.onreadystatechange _this.Estados.Change;
        
_this.Handler.send((metodo.toUpperCase() == 'POST') ? parametros null);
    }
    
    
_this.Estados.Show = function(objIdmsj)
    {
        
//segun el tipo de objeto decido entre usar innerHTML o value
        
if(document.getElementById(objId).tagName == 'DIV') {
            
document.getElementById(objId).innerHTML msj;
        }
        if(
document.getElementById(objId).tagName == 'INPUT') {
            
document.getElementById(objId).value msj;
        }
    }
    
    
//SETEAR LOS MENSAJES A MOSTRAR
    
_this.SetMsj = function(tipoEstadoobjIdmsj)
    {
        
_this.Estados.Tipos[tipoEstado].Msj msj;
        
_this.Estados.Tipos[tipoEstado].ObjId objId;
    }
    
_this.SetDestino = function(objId)
    {
        
_this.Estados.Tipos['DESTINO'].ObjId objId;    
    }
}

window.onload = function()
{
    
/*
    * IMPLEMENTACION
    */
    
pagina = new Ajax();
    
pagina.SetMsj('CARGANDO''estado''Cargando...');
    
pagina.SetMsj('COMPLETO''estado''Completado con Exito!!');
    
pagina.SetDestino('carga');
}
</script>
</head>

<body>
<input id="hola" onclick="pagina.Enviar('ejemplo.php', 'GET');" type="button" value="Cargar" />
<div id="estado">Sin acciones</div>
<div id="carga"></div>
</body>
</html> 
Bueno cualquier critica constructiva, y cualquier ayuda para aprender y mejorar mi codigo es aceptada!

Gracias desde ya!
  #15 (permalink)  
Antiguo 11/08/2008, 10:15
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 11 meses
Puntos: 2135
Respuesta: Alguien me ayuda a mejorar esto

Hola korg1988,

Por favor continua sobre el mismo tema.

Saludos.
  #16 (permalink)  
Antiguo 12/08/2008, 06:55
Avatar de korg1988  
Fecha de Ingreso: junio-2006
Ubicación: Santa Fe, Argentina
Mensajes: 825
Antigüedad: 17 años, 9 meses
Puntos: 19
Respuesta: Alguien me ayuda a mejorar esto

esta bien GatorV
Alguna ayuda? de alguien ?
  #17 (permalink)  
Antiguo 13/08/2008, 22:33
Avatar de korg1988  
Fecha de Ingreso: junio-2006
Ubicación: Santa Fe, Argentina
Mensajes: 825
Antigüedad: 17 años, 9 meses
Puntos: 19
Respuesta: Alguien me ayuda a mejorar esto

segui en este tema y quedo perdido nadie mas dijo nada!

Alguien tiene alguna opinion? alguna ayuda?!
  #18 (permalink)  
Antiguo 14/08/2008, 07:58
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 11 meses
Puntos: 2135
Respuesta: Alguien me ayuda a mejorar esto

Hola korg1988,

¿Podrías ser claro y especificar sobre que tienes problemas?

Saludos.
  #19 (permalink)  
Antiguo 15/08/2008, 08:55
Avatar de korg1988  
Fecha de Ingreso: junio-2006
Ubicación: Santa Fe, Argentina
Mensajes: 825
Antigüedad: 17 años, 9 meses
Puntos: 19
Respuesta: Alguien me ayuda a mejorar esto

no es que tenga problemas sobre algo, el codigo asi como esta funciona, pero queria optimizarlo! porque quiza haya cosas que seria mejor hacerlas de otra manera!

Eso es solamente lo que pedia, una ayuda para mejorar mi codigo!

Saludos gator
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta

SíEste tema le ha gustado a 1 personas




La zona horaria es GMT -6. Ahora son las 16:25.