Foros del Web » Programando para Internet » Javascript »

Problema Variable Global

Estas en el tema de Problema Variable Global en el foro de Javascript en Foros del Web. Tengo un pequeño gran problema en mi codigo tengo declaradas 3 variables globales que se les va asignando valores en distintas funciones, en teoria deberia ...
  #1 (permalink)  
Antiguo 11/06/2012, 09:29
 
Fecha de Ingreso: marzo-2012
Mensajes: 28
Antigüedad: 12 años
Puntos: 1
Exclamación Problema Variable Global

Tengo un pequeño gran problema en mi codigo tengo declaradas 3 variables globales que se les va asignando valores en distintas funciones, en teoria deberia poder utilizar su contenido en cualquier funcion debido a que son globales, pero el intentar usarlas no contienen ningun valor.

Este es mi codigo

Código HTML:
<script type="text/javascript">
           var v=[];
            var v2=[];
            var dia=[];
            
           function recibe(name){
                var regexS = "[\\?&]"+name+"=([^&#]*)";
                var regex = new RegExp ( regexS );
                var tmpURL = window.location.href;
                var results = regex.exec( tmpURL );
                if( results == null )
    		        return "";
    	        else
    		        return results[1];
            }
           
            function callTheJsonp()
            {
                var reci=recibe('periodo');
                var url = "http://www.trueware.mx/eduardo/mycommerce/ventadiaria.php?callback=parseRequest&periodo="+reci;
                var script = document.createElement('script');
                script.setAttribute('src', url);
                document.getElementsByTagName('head')[0].appendChild(script);
            }
           
           function parseRequest(response)
            {
                try
                {
                    console.log(response);
                    var venta=[];
                    var prod=[];
                    var acum=0;
    				for (var i=0; i < response.length; i++) 
                    {
						venta[i] = eval(response[i].venta);
                        prod[i] = eval(response[i].dia);
                        acum=acum+venta[i]; 
					}
                    for(var i=0; i < 32; i++)
                    {
                        v[i]=0;
                        dia[i]=i;
                    }
                    for (var i=0; i < prod.length; i++) 
                    {
                        v[prod[i]]=venta[i];
                    }
                    var li = document.createElement("LI");
                    li.innerHTML = '<font size=2>'+'Venta Total: '+acum+'</font>';
                    var ul = document.getElementById("contenido");
                    ul.appendChild(li);
                }
                catch(an_exception)
                {
                    document.write("Error de Conexion");
                }
            }
            function callTheJsonp2()
            {
                var reci=recibe('periodo');
                var url = "http://www.trueware.mx/eduardo/mycommerce/ventadiaria12.php?callback=parseRequest2&periodo="+reci;
                var script = document.createElement('script');
                script.setAttribute('src', url);
                document.getElementsByTagName('head')[0].appendChild(script);
            }
           
           function parseRequest2(response)
            {
                try
                {
                    console.log(response);
                    var venta=[];
                    var prod=[];
        			for (var i=0; i < response.length; i++) 
                    {
						venta[i] = eval(response[i].venta);
                        prod[i] = eval(response[i].dia);
					}
                    for(var i=0; i < 32; i++)
                    {
                        v2[i]=0;
                    }
                    for (var i=0; i < prod.length; i++) 
                    {
                        v2[prod[i]]=venta[i];
                    }
                }
                catch(an_exception)
                {
                    document.write("Error de Conexion");
                }
            }
            function grafica(venta,venta2,dia)
            {
                var line1 = new RGraph.Line('line1', venta,venta2);
                line1.Set('chart.background.grid', true);
                line1.Set('chart.linewidth', 5);
                line1.Set('chart.gutter.left', 35);
                line1.Set('chart.hmargin', 5);
                line1.Set('chart.tickmarks', 'circle');
                line1.Set('chart.units.post', '$');
                line1.Set('chart.colors', ['red', 'green']);
                //line1.Set('chart.curvy', 1);
                line1.Set('chart.curvy.factor', 0.25);
                line1.Set('chart.labels',dia);
                line1.Set('chart.background.grid.hlines', false);
                line1.Set('chart.background.grid.autofit.numvlines', 11);
                line1.Draw();
            }
            function primero()
           {
               callTheJsonp();
               callTheJsonp2();
               alert(v);
               alert(v2);
               alert(dia);
               grafica(v,v2,dia);
               
           }
</script> 
desde mi body llamo a la funcion primero <body onload="primero()">

puse alert para verificar su contenido de dichas variables y no contienen nada.

Alguna idea, alguien que vea mi error
  #2 (permalink)  
Antiguo 11/06/2012, 09:59
Avatar de Heiroon  
Fecha de Ingreso: junio-2010
Ubicación: Caracas, Venezuela - Por ahora...
Mensajes: 495
Antigüedad: 13 años, 10 meses
Puntos: 63
Exclamación Respuesta: Problema Variable Global

No estoy seguro de que te solucione el problema, pero prueba quitando los var.

Saludos...
__________________
Gmail : [email protected]
Twitter: @heiroon

I'm back!
  #3 (permalink)  
Antiguo 11/06/2012, 11:06
Avatar de cristian_cena
Colaborador
 
Fecha de Ingreso: junio-2009
Mensajes: 2.244
Antigüedad: 14 años, 10 meses
Puntos: 269
Respuesta: Problema Variable Global

No estas pasando las variables como argumento a la función primero().
Ejemplo:
Código Javascript:
Ver original
  1. var v = "hola";
  2.  
  3. function primero(v)
  4. {
  5.    return v;  
  6. }
  7.  
  8. window.onload = function(){
  9.     alert(v);         //"hola"
  10.     alert(primero()); // undefined
  11.     alert(primero(v));//"hola"
  12. }

En este ejemplo si no existiera el argumento "v" de la función "primero" ésta retornará undefined ya que "v" en el interior es un identificador de una variable/función no definida.

Saludos
  #4 (permalink)  
Antiguo 11/06/2012, 13:58
Avatar de IsaBelM
Colaborador
 
Fecha de Ingreso: junio-2008
Mensajes: 5.032
Antigüedad: 15 años, 10 meses
Puntos: 1012
Respuesta: Problema Variable Global

he leído el código por encima.
esas variables son objetos y estos objetos se rellenan ejecutando la función parseRequest(), que nunca es invocada. por lo tanto al alertar las variables, éstas están vacías
__________________
if(ViolenciaDeGénero) {alert('MUJER ASESINADA');}
  #5 (permalink)  
Antiguo 11/06/2012, 15:18
 
Fecha de Ingreso: marzo-2012
Mensajes: 28
Antigüedad: 12 años
Puntos: 1
Respuesta: Problema Variable Global

se rellenan en parseRequest() efectivamente la funcion es llamada desde calljsonP() (como parametro que recibo en php), de hecho si hago un alert() ahi si tienen el valor, es un envio de json por eso la llamo de esta forma, algun otra idea, y no las paso como parametro porque se supone que son globales, necesito hacerlo de esa forma, de hecho si lo hago como mencionas cristian_cena el resultado del alert es undefined y si la uso como global el alert no muestra nada.
  #6 (permalink)  
Antiguo 11/06/2012, 15:39
Avatar de Lynxcraft  
Fecha de Ingreso: noviembre-2007
Ubicación: yecla murcia
Mensajes: 1.346
Antigüedad: 16 años, 5 meses
Puntos: 51
Respuesta: Problema Variable Global

no se pero podrías evitar conflictos por nombres como poe ejemplo poner esto

Código PHP:
var __v=[];
var 
__v2=[];
var 
__dia=[]; 
de esta manera que aseguras de que únicas como te muestra el ejemplo cristian_cena

si estas cargando las variables con valores obtenidos por medio de ajax y json o simplemente cargas un nuevo script ,ahi el esta problema ya que este proceso tarda un tiempo en ejecutarse por lo que las funciones dentro de la pagina terminaran de ejecutarse antes de que la petición con los nuevos valores llegue, por lo que tienes que hacer es cargarlas primero,

Código PHP:
<script type="text/javascript">
function 
loadScript(urlcallback){
    
    var 
script document.createElement("script");
    
script.type "text/javascript";
    if (
script.readyState){  //IE
        
script.onreadystatechange = function(){
            if (
script.readyState == "loaded" ||
                    
script.readyState == "complete"){
                
script.onreadystatechange null;
                if(
typeof callback == "function"
                    
callback();
            }
        };
    } else {  
//Others
        
script.onload = function(){
           if(
typeof callback == "function")
                
callback();
        };
    }
    
script.src url;
    
document.getElementsByTagName("head")[0].appendChild(script);
}

var 
v=[];
var 
v2=[];
var 
dia=[];
            
           function 
recibe(name){
                var 
regexS "[\\?&]"+name+"=([^&#]*)";
                var 
regex = new RegExp regexS );
                var 
tmpURL window.location.href;
                var 
results regex.exectmpURL );
                if( 
results == null )
                    return 
"";
                else
                    return 
results[1];
            }
           
            function 
callTheJsonp(fn){
                var 
reci=recibe('periodo');
                var 
url "http://www.trueware.mx/eduardo/mycommerce/ventadiaria.php?callback=parseRequest&periodo="+reci;
                
loadScript(url,fn);
            }
           
           function 
parseRequest(response)
            {
                try
                {
                    
console.log(response);
                    var 
venta=[];
                    var 
prod=[];
                    var 
acum=0;
                    for (var 
i=0response.lengthi++) 
                    {
                        
venta[i] = eval(response[i].venta);
                        
prod[i] = eval(response[i].dia);
                        
acum=acum+venta[i]; 
                    }
                    for(var 
i=032i++)
                    {
                        
v[i]=0;
                        
dia[i]=i;
                    }
                    for (var 
i=0prod.lengthi++) 
                    {
                        
v[prod[i]]=venta[i];
                    }
                    var 
li document.createElement("LI");
                    
li.innerHTML '<font size=2>'+'Venta Total: '+acum+'</font>';
                    var 
ul document.getElementById("contenido");
                    
ul.appendChild(li);
                }
                catch(
an_exception)
                {
                    
document.write("Error de Conexion");
                }
            }
            function 
callTheJsonp2(fn)
            {
                var 
reci=recibe('periodo');
                var 
url "http://www.trueware.mx/eduardo/mycommerce/ventadiaria12.php?callback=parseRequest2&periodo="+reci;
          
                
                
loadScript(url,fn);
            }
           
           function 
parseRequest2(response)
            {
                try
                {
                    
console.log(response);
                    var 
venta=[];
                    var 
prod=[];
                    for (var 
i=0response.lengthi++) 
                    {
                        
venta[i] = eval(response[i].venta);
                        
prod[i] = eval(response[i].dia);
                    }
                    for(var 
i=032i++)
                    {
                        
v2[i]=0;
                    }
                    for (var 
i=0prod.lengthi++) 
                    {
                        
v2[prod[i]]=venta[i];
                    }
                }
                catch(
an_exception)
                {
                    
document.write("Error de Conexion");
                }
            }
            function 
grafica(venta,venta2,dia)
            {
                var 
line1 = new RGraph.Line('line1'venta,venta2);
                
line1.Set('chart.background.grid'true);
                
line1.Set('chart.linewidth'5);
                
line1.Set('chart.gutter.left'35);
                
line1.Set('chart.hmargin'5);
                
line1.Set('chart.tickmarks''circle');
                
line1.Set('chart.units.post''$');
                
line1.Set('chart.colors', ['red''green']);
                
//line1.Set('chart.curvy', 1);
                
line1.Set('chart.curvy.factor'0.25);
                
line1.Set('chart.labels',dia);
                
line1.Set('chart.background.grid.hlines'false);
                
line1.Set('chart.background.grid.autofit.numvlines'11);
                
line1.Draw();
            }
            function 
primero()
           {
               
callTheJsonp(function(){
                    
callTheJsonp2(function(){
                           
alert(v);
                           
alert(v2);
                           
alert(dia);
                           
grafica(v,v2,dia);
                    });
               });
              ;
               
               
           }

</script> 
__________________
Sobran las ideas cuando faltan ganas de trabajar en ellas
Lynxcraft
  #7 (permalink)  
Antiguo 12/06/2012, 16:18
 
Fecha de Ingreso: marzo-2012
Mensajes: 28
Antigüedad: 12 años
Puntos: 1
Respuesta: Problema Variable Global

Muchas gracias Lynxcraft efectivamente el problema era ese no alcanzaba a recibir respuesta del contenido a utilizar, nuevamente gracias por tomar el tiempo para apoyarme

Etiquetas: funcion, global, html, js, php, variables
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




La zona horaria es GMT -6. Ahora son las 19:50.