Foros del Web » Programando para Internet » Jquery »

[SOLUCIONADO] Convertir código a JQuery

Estas en el tema de Convertir código a JQuery en el foro de Jquery en Foros del Web. Hola por favor tengo un código que me gustaría convertirlo a jQuery . Se podría hacer?. Como podría hacerlo ? @import url("http://static.forosdelweb.com/clientscript/vbulletin_css/geshi.css"); Código Javascript : ...
  #1 (permalink)  
Antiguo 22/01/2014, 12:33
Avatar de satjaen  
Fecha de Ingreso: septiembre-2012
Ubicación: Jaén (Andalucía)
Mensajes: 893
Antigüedad: 11 años, 7 meses
Puntos: 10
Convertir código a JQuery

Hola por favor tengo un código que me gustaría convertirlo a jQuery . Se podría hacer?. Como podría hacerlo ?

Código Javascript:
Ver original
  1. function valida_envia(e)
  2. {
  3.   if (window.event)
  4.     window.event.returnValue=false;
  5.   else
  6.     if (e)
  7.       e.preventDefault();
  8.   enviarFormulario();
  9. }
  10.  
  11. var conexion1;
  12. function enviarFormulario()
  13. {
  14.   conexion1=crearXMLHttpRequest()
  15.   conexion1.onreadystatechange = procesarEventos;
  16.   var telefonos = document.forms['datos'].elements['telefonos'];
  17.   alert('Valor de la propiedad readyState:'+conexion1.readyState);
  18.   conexion1.open("GET", "val_telef.php?telefonos=" + telefonos.value, false);
  19.   conexion1.send(null);  
  20. }
  21.  
  22.         function procesarEventos()
  23.         {
  24.         alert('Valor de la propiedad readyState:'+conexion1.readyState);
  25.         var resultados = document.getElementById("carga1");
  26.         if(conexion1.readyState == 4)
  27.         {
  28.         resultados.innerHTML = conexion1.responseText;
  29.        
  30.    
  31.        
  32.          var xml = conexion1.responseXML;
  33.             dato=xml.getElementsByTagName("datos");
  34.             if(dato[0].firstChild.nodeValue=="1")
  35.             {
  36.                 num_user=xml.getElementsByTagName("numusuario");
  37.                
  38.                
  39.                 document.getElementById("movil").value =xml.getElementsByTagName("movil")[0].firstChild.nodeValue;
  40.                 document.getElementById("calle").value =xml.getElementsByTagName("calle")[0].firstChild.nodeValue;
  41.                 document.getElementById("dni").value =xml.getElementsByTagName("dni")[0].firstChild.nodeValue;
  42.                 document.getElementById("name").value =xml.getElementsByTagName("name")[0].firstChild.nodeValue;
  43.                 document.getElementById("edificio").value =xml.getElementsByTagName("edificio")[0].firstChild.nodeValue;
  44.                 document.getElementById("numero").value =xml.getElementsByTagName("numero")[0].firstChild.nodeValue;
  45.                 document.getElementById("puerta").value =xml.getElementsByTagName("puerta")[0].firstChild.nodeValue;
  46.                 document.getElementById("piso").value =xml.getElementsByTagName("piso")[0].firstChild.nodeValue;
  47.                 document.getElementById("letra").value =xml.getElementsByTagName("letra")[0].firstChild.nodeValue;
  48.                 document.getElementById("localidad").value =xml.getElementsByTagName("localidad")[0].firstChild.nodeValue;
  49.                 document.getElementById("provincia").value =xml.getElementsByTagName("provincia")[0].firstChild.nodeValue;
  50.                 document.getElementById("email").value =xml.getElementsByTagName("email")[0].firstChild.nodeValue;
  51.                
  52.            
  53.                  
  54.        
  55.             }
  56.    
  57.         }
  58.         else
  59.         if (conexion1.readyState==1 || conexion1.readyState==2 || conexion1.readyState==3)
  60.         {
  61.         resultados.innerHTML = "<img src='imagenes_menu/ajax-loader4.gif' align='center' /><br />Cargando...";
  62.            }
  63.         }
  64.      
  65.  
  66.     function crearXMLHttpRequest()
  67. {
  68.   var xmlHttp=null;
  69.   if (window.ActiveXObject)
  70.     xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  71.   else
  72.     if (window.XMLHttpRequest)
  73.       xmlHttp = new XMLHttpRequest();
  74.   return xmlHttp;
  75. }


Gracias y un saludo
  #2 (permalink)  
Antiguo 22/01/2014, 13:24
Avatar de maycolalvarez
Colaborador
 
Fecha de Ingreso: julio-2008
Ubicación: Caracas
Mensajes: 12.120
Antigüedad: 15 años, 9 meses
Puntos: 1532
Respuesta: Convertir código a JQuery

no hace falta usar jQuery para que AJAX funcione, si revisas la documentación de la técnica sólo te falta evaluar el xhr.status == 200 junto con el xhr.readyState == 4, consulta un manual de AJAX

en la línea 26 tendrías:

Código Javascript:
Ver original
  1. if(conexion1.readyState == 4 && conexion1.status == 200 )
  2. //...
__________________
¡Por favor!: usa el highlight para mostrar código
El que busca, encuentra...
  #3 (permalink)  
Antiguo 22/01/2014, 13:29
Avatar de satjaen  
Fecha de Ingreso: septiembre-2012
Ubicación: Jaén (Andalucía)
Mensajes: 893
Antigüedad: 11 años, 7 meses
Puntos: 10
Respuesta: Convertir código a JQuery

Cita:
Iniciado por maycolalvarez Ver Mensaje
no hace falta usar jQuery para que AJAX funcione, si revisas la documentación de la técnica sólo te falta evaluar el xhr.status == 200 junto con el xhr.readyState == 4, consulta un manual de AJAX
Gracias Maycol, el código funciona en Firefox pero en Chrome no. El problema lo tengo en la imagen de carga que sale cuando el estado es 1. Y por eso es querer hacerlo en jQuery
  #4 (permalink)  
Antiguo 22/01/2014, 14:24
Avatar de satjaen  
Fecha de Ingreso: septiembre-2012
Ubicación: Jaén (Andalucía)
Mensajes: 893
Antigüedad: 11 años, 7 meses
Puntos: 10
Respuesta: Convertir código a JQuery

Maycol lo he puesto como me has dicho pero sigue sin salir en Google Chrome la imagen de cargando......

Código Javascript:
Ver original
  1. function valida_envia(e)
  2. {
  3.    
  4.      var telefonos = document.forms['datos'].elements['telefonos'];
  5.     if (telefonos.value.length == 0)
  6.     {
  7.        
  8.         alert("Insertar el nº de teléfono");
  9.  
  10.         telefonos.focus();
  11.  
  12.         return 0;
  13.  
  14.     }
  15.     else
  16.     {
  17.   if (window.event)
  18.     window.event.returnValue=false;
  19.   else
  20.     if (e)
  21.       e.preventDefault();
  22.   enviarFormulario();
  23. }
  24.  
  25. var conexion1;
  26. function enviarFormulario()
  27. {
  28.   conexion1=crearXMLHttpRequest()
  29.   conexion1.onreadystatechange = procesarEventos;
  30.   conexion1.open("GET", "val_telef.php?telefonos=" + telefonos.value, false);
  31.   conexion1.send(null);  
  32. }
  33.  
  34.         function procesarEventos()
  35.         {
  36.         var resultados = document.getElementById("carga1");
  37.         if(conexion1.readyState == 4 && conexion1.status == 200 )
  38.         {
  39.         resultados.innerHTML = conexion1.responseText;
  40.        
  41.    
  42.        
  43.          var xml = conexion1.responseXML;
  44.             dato=xml.getElementsByTagName("datos");
  45.             if(dato[0].firstChild.nodeValue=="1")
  46.             {
  47.                 num_user=xml.getElementsByTagName("numusuario");
  48.                
  49.                
  50.                 document.getElementById("movil").value =xml.getElementsByTagName("movil")[0].firstChild.nodeValue;
  51.                 document.getElementById("calle").value =xml.getElementsByTagName("calle")[0].firstChild.nodeValue;
  52.                 document.getElementById("dni").value =xml.getElementsByTagName("dni")[0].firstChild.nodeValue;
  53.                 document.getElementById("name").value =xml.getElementsByTagName("name")[0].firstChild.nodeValue;
  54.                 document.getElementById("edificio").value =xml.getElementsByTagName("edificio")[0].firstChild.nodeValue;
  55.                 document.getElementById("numero").value =xml.getElementsByTagName("numero")[0].firstChild.nodeValue;
  56.                 document.getElementById("puerta").value =xml.getElementsByTagName("puerta")[0].firstChild.nodeValue;
  57.                 document.getElementById("piso").value =xml.getElementsByTagName("piso")[0].firstChild.nodeValue;
  58.                 document.getElementById("letra").value =xml.getElementsByTagName("letra")[0].firstChild.nodeValue;
  59.                 document.getElementById("localidad").value =xml.getElementsByTagName("localidad")[0].firstChild.nodeValue;
  60.                 document.getElementById("provincia").value =xml.getElementsByTagName("provincia")[0].firstChild.nodeValue;
  61.                 document.getElementById("email").value =xml.getElementsByTagName("email")[0].firstChild.nodeValue;
  62.                
  63.            
  64.                  
  65.        
  66.             }else(dato[0].firstChild.nodeValue=="0")
  67.             {                  
  68.                      envia();
  69.                          }
  70.        
  71.  
  72.         }
  73.         else
  74.         if (conexion1.readyState==1 || conexion1.readyState==2 || conexion1.readyState==3)
  75.         {
  76.         resultados.innerHTML = "<img src='imagenes_menu/ajax-loader4.gif' align='center' /><br />Cargando...";
  77.            }
  78.         }
  79.      
  80.  
  81.     function crearXMLHttpRequest()
  82. {
  83.   var xmlHttp=null;
  84.   if (window.ActiveXObject)
  85.     xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  86.   else
  87.     if (window.XMLHttpRequest)
  88.       xmlHttp = new XMLHttpRequest();
  89.   return xmlHttp;
  90.    }    
  91. }
  #5 (permalink)  
Antiguo 23/01/2014, 16:04
Avatar de satjaen  
Fecha de Ingreso: septiembre-2012
Ubicación: Jaén (Andalucía)
Mensajes: 893
Antigüedad: 11 años, 7 meses
Puntos: 10
Respuesta: Convertir código a JQuery

He modificado el código y añadiendo css con jQuery pero sigue sin salirme la imagen del loading en Google Chrome. Por favor,nadie sabe lo que ocurre ?

Código Javascript:
Ver original
  1. if (conexion1.readyState==1 || conexion1.readyState==2 || conexion1.readyState==3)
  2.         {
  3.          $('#carga').css({
  4.                 opacity:1,
  5.                 display:'block'
  6.                
  7.             });
  8.          $('#fondo').css({
  9.                 opacity:.25
  10.             });
  11.          
  12.  
  13. if(conexion1.readyState == 4 && conexion1.status == 200 )
  14.         {
  15.            $('#fondo').css({
  16.                 opacity:1
  17.             });
  18.           $('#carga').css('display','none');


Código Javascript:
Ver original
  1. function valida_envia(e)
  2. {
  3.    
  4.      var telefonos = document.forms['datos'].elements['telefonos'];
  5.     if (telefonos.value.length == 0)
  6.     {
  7.        
  8.         alert("Insertar el nº de teléfono");
  9.  
  10.         telefonos.focus();
  11.  
  12.         return 0;
  13.  
  14.     }
  15.     else
  16.     {
  17.   if (window.event)
  18.     window.event.returnValue=false;
  19.   else
  20.     if (e)
  21.       e.preventDefault();
  22.   enviarFormulario();
  23. }
  24.  
  25. var conexion1;
  26. function enviarFormulario()
  27. {
  28.   conexion1=crearXMLHttpRequest()
  29.   conexion1.onreadystatechange = procesarEventos;
  30.   conexion1.open("GET", "val_telef.php?telefonos=" + telefonos.value, false);
  31.   conexion1.send(null);  
  32. }
  33.  
  34.         function procesarEventos()
  35.         {
  36.         var resultados = document.getElementById("carga");
  37.         if(conexion1.readyState == 4 && conexion1.status == 200 )
  38.         {
  39.            $('#fondo').css({
  40.                 opacity:1
  41.             });
  42.           $('#carga').css('display','none');
  43.         resultados.innerHTML = conexion1.responseText;
  44.        
  45.    
  46.        
  47.          var xml = conexion1.responseXML;
  48.             dato=xml.getElementsByTagName("datos");
  49.             if(dato[0].firstChild.nodeValue=="1")
  50.             {
  51.                 num_user=xml.getElementsByTagName("numusuario");
  52.                
  53.                
  54.                 document.getElementById("movil").value =xml.getElementsByTagName("movil")[0].firstChild.nodeValue;
  55.                 document.getElementById("calle").value =xml.getElementsByTagName("calle")[0].firstChild.nodeValue;
  56.                 document.getElementById("dni").value =xml.getElementsByTagName("dni")[0].firstChild.nodeValue;
  57.                 document.getElementById("name").value =xml.getElementsByTagName("name")[0].firstChild.nodeValue;
  58.                 document.getElementById("edificio").value =xml.getElementsByTagName("edificio")[0].firstChild.nodeValue;
  59.                 document.getElementById("numero").value =xml.getElementsByTagName("numero")[0].firstChild.nodeValue;
  60.                 document.getElementById("puerta").value =xml.getElementsByTagName("puerta")[0].firstChild.nodeValue;
  61.                 document.getElementById("piso").value =xml.getElementsByTagName("piso")[0].firstChild.nodeValue;
  62.                 document.getElementById("letra").value =xml.getElementsByTagName("letra")[0].firstChild.nodeValue;
  63.                 document.getElementById("localidad").value =xml.getElementsByTagName("localidad")[0].firstChild.nodeValue;
  64.                 document.getElementById("provincia").value =xml.getElementsByTagName("provincia")[0].firstChild.nodeValue;
  65.                 document.getElementById("email").value =xml.getElementsByTagName("email")[0].firstChild.nodeValue;
  66.                
  67.            
  68.                  
  69.        
  70.             }else(dato[0].firstChild.nodeValue=="0")
  71.             {                  
  72.                      envia();
  73.                          }
  74.        
  75.  
  76.         }
  77.         else
  78.         if (conexion1.readyState==1 || conexion1.readyState==2 || conexion1.readyState==3)
  79.         {
  80.          $('#carga').css({
  81.                 opacity:1,
  82.                 display:'block'
  83.                
  84.             });
  85.          $('#fondo').css({
  86.                 opacity:.25
  87.             });
  88.          
  89.            }
  90.         }
  91.      
  92.  
  93.     function crearXMLHttpRequest()
  94. {
  95.   var xmlHttp=null;
  96.   if (window.ActiveXObject)
  97.     xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  98.   else
  99.     if (window.XMLHttpRequest)
  100.       xmlHttp = new XMLHttpRequest();
  101.   return xmlHttp;
  102.    }    
  103. }
  #6 (permalink)  
Antiguo 23/01/2014, 16:17
Avatar de Alexis88
Philosopher
 
Fecha de Ingreso: noviembre-2011
Ubicación: Tacna, Perú
Mensajes: 5.552
Antigüedad: 12 años, 5 meses
Puntos: 977
Respuesta: Convertir código a JQuery

Así fue como lo hice y funcionó bien en todos los navegadores:

Código Javascript:
Ver original
  1. xhr.onreadystatechange = function(){
  2.     var salida = document.getElementById("salida"), //El DIV
  3.         gifCarga = document.getElementById("gifCarga"); //El GIF
  4.  
  5.     if (xhr.readyState < 4)
  6.         salida.innerHTML = gifCarga;
  7.     else
  8.         setTimeout(function(){
  9.             var respuesta = xhr.status == 200 ? xhr.responseText : xhr.status == 400 ? "La dirección brindada no existe" : "Error: " + xhr.status;
  10.             salida.innerHTML = respuesta;
  11.         }, 2000);
  12. };

Adecualo a tu código, saludos.
__________________
«Juro por mi vida y mi amor por ella, que jamás viviré para el provecho de otro hombre, ni le pediré a otro hombre que viva para el mío».

Ayn Rand
  #7 (permalink)  
Antiguo 23/01/2014, 16:37
Avatar de satjaen  
Fecha de Ingreso: septiembre-2012
Ubicación: Jaén (Andalucía)
Mensajes: 893
Antigüedad: 11 años, 7 meses
Puntos: 10
Respuesta: Convertir código a JQuery

Cita:
Iniciado por Alexis88 Ver Mensaje
Así fue como lo hice y funcionó bien en todos los navegadores:

Código Javascript:
Ver original
  1. xhr.onreadystatechange = function(){
  2.     var salida = document.getElementById("salida"), //El DIV
  3.         gifCarga = document.getElementById("gifCarga"); //El GIF
  4.  
  5.     if (xhr.readyState < 4)
  6.         salida.innerHTML = gifCarga;
  7.     else
  8.         setTimeout(function(){
  9.             var respuesta = xhr.status == 200 ? xhr.responseText : xhr.status == 400 ? "La dirección brindada no existe" : "Error: " + xhr.status;
  10.             salida.innerHTML = respuesta;
  11.         }, 2000);
  12. };

Adecualo a tu código, saludos.

Perdona, Alexis pero no llego a modificarlo.
  #8 (permalink)  
Antiguo 23/01/2014, 16:46
Avatar de Alexis88
Philosopher
 
Fecha de Ingreso: noviembre-2011
Ubicación: Tacna, Perú
Mensajes: 5.552
Antigüedad: 12 años, 5 meses
Puntos: 977
Respuesta: Convertir código a JQuery

Lo único que tienes que cambiar es lo que va adentro de la función del setTimeout por lo que ejecutas en tu función cuando readyState es 4 y state es 200, eso es todo.
__________________
«Juro por mi vida y mi amor por ella, que jamás viviré para el provecho de otro hombre, ni le pediré a otro hombre que viva para el mío».

Ayn Rand
  #9 (permalink)  
Antiguo 23/01/2014, 17:03
Avatar de satjaen  
Fecha de Ingreso: septiembre-2012
Ubicación: Jaén (Andalucía)
Mensajes: 893
Antigüedad: 11 años, 7 meses
Puntos: 10
Respuesta: Convertir código a JQuery

Cita:
Iniciado por Alexis88 Ver Mensaje
Lo único que tienes que cambiar es lo que va adentro de la función del setTimeout por lo que ejecutas en tu función cuando readyState es 4 y state es 200, eso es todo.
Me he liado , no parece tan facil. No te pongo lo que he hecho porque esta mal seguro.
  #10 (permalink)  
Antiguo 23/01/2014, 17:12
Avatar de Alexis88
Philosopher
 
Fecha de Ingreso: noviembre-2011
Ubicación: Tacna, Perú
Mensajes: 5.552
Antigüedad: 12 años, 5 meses
Puntos: 977
Respuesta: Convertir código a JQuery

Hazlo con calma, revisa línea por línea para ver qué estás haciendo mal, peor será si lo haces apurado, porque no notarás los errores.
__________________
«Juro por mi vida y mi amor por ella, que jamás viviré para el provecho de otro hombre, ni le pediré a otro hombre que viva para el mío».

Ayn Rand
  #11 (permalink)  
Antiguo 23/01/2014, 17:20
Avatar de satjaen  
Fecha de Ingreso: septiembre-2012
Ubicación: Jaén (Andalucía)
Mensajes: 893
Antigüedad: 11 años, 7 meses
Puntos: 10
Respuesta: Convertir código a JQuery

Pero Alexis, tengo que poner todo esto no?

Código Javascript:
Ver original
  1. function valida_envia(e)
  2. {
  3.    
  4.      var telefonos = document.forms['datos'].elements['telefonos'];
  5.     if (telefonos.value.length == 0)
  6.     {
  7.        
  8.         alert("Insertar el nº de teléfono");
  9.  
  10.         telefonos.focus();
  11.  
  12.         return 0;
  13.  
  14.     }
  15.     else
  16.     {
  17.   if (window.event)
  18.     window.event.returnValue=false;
  19.   else
  20.     if (e)
  21.       e.preventDefault();
  22.   enviarFormulario();
  23. }
  24.  
  25. var conexion1;
  26. function enviarFormulario()
  27. {
  28.   conexion1=crearXMLHttpRequest()
  29.   conexion1.onreadystatechange = procesarEventos;
  30.   conexion1.open("GET", "val_telef.php?telefonos=" + telefonos.value, false);
  31.   conexion1.send(null);  
  32. }
  33.  
  34.         function procesarEventos()
  35.         {
  36.            
  37.            
  38.         var resultados = document.getElementById("carga");


Y luego:

Código Javascript:
Ver original
  1. xhr.onreadystatechange = function(){
  2.     var salida = document.getElementById("salida"), //El DIV
  3.         gifCarga = document.getElementById("gifCarga"); //El GIF
  4.  
  5.  if (xhr.readyState < 4)
  6.  
  7.  $('#carga').css({
  8.                 opacity:1,
  9.                 display:'block'
  10.                
  11.             });
  12.          $('#fondo').css({
  13.                 opacity:.25
  14.             });
  15.  
  16.         salida.innerHTML = gifCarga;
  17.  
  18.  else
  19.  
  20.         setTimeout(function(){
  21.             var respuesta = xhr.status == 200 ? xhr.responseText : xhr.status == 400 ? "La dirección brindada no existe" : "Error: " + xhr.status;
  22.             salida.innerHTML = respuesta;
  23.  
  24.  
  25.  
  26. $('#fondo').css({
  27.                 opacity:1
  28.             });
  29.           $('#carga').css('display','none');
  30.          
  31.         resultados.innerHTML = conexion1.responseText;
  32.        
  33.    
  34.        
  35.          var xml = conexion1.responseXML;
  36.             dato=xml.getElementsByTagName("datos");
  37.             if(dato[0].firstChild.nodeValue=="1")
  38.             {
  39.                 num_user=xml.getElementsByTagName("numusuario");
  40.                
  41.                
  42.                 document.getElementById("movil").value =xml.getElementsByTagName("movil")[0].firstChild.nodeValue;
  43.                 document.getElementById("calle").value =xml.getElementsByTagName("calle")[0].firstChild.nodeValue;
  44.                 document.getElementById("dni").value =xml.getElementsByTagName("dni")[0].firstChild.nodeValue;
  45.                 document.getElementById("name").value =xml.getElementsByTagName("name")[0].firstChild.nodeValue;
  46.                 document.getElementById("edificio").value =xml.getElementsByTagName("edificio")[0].firstChild.nodeValue;
  47.                 document.getElementById("numero").value =xml.getElementsByTagName("numero")[0].firstChild.nodeValue;
  48.                 document.getElementById("puerta").value =xml.getElementsByTagName("puerta")[0].firstChild.nodeValue;
  49.                 document.getElementById("piso").value =xml.getElementsByTagName("piso")[0].firstChild.nodeValue;
  50.                 document.getElementById("letra").value =xml.getElementsByTagName("letra")[0].firstChild.nodeValue;
  51.                 document.getElementById("localidad").value =xml.getElementsByTagName("localidad")[0].firstChild.nodeValue;
  52.                 document.getElementById("provincia").value =xml.getElementsByTagName("provincia")[0].firstChild.nodeValue;
  53.                 document.getElementById("email").value =xml.getElementsByTagName("email")[0].firstChild.nodeValue;
  54.                
  55.            
  56.                  
  57.        
  58.             }else(dato[0].firstChild.nodeValue=="0")
  59.             {                  
  60.                      envia();
  61.                          }
  62.  
  63.  
  64.         }, 2000);
  65. };


Y luego tengo que añadir tambien:

Código Javascript:
Ver original
  1. function crearXMLHttpRequest()
  2. {
  3.   var xmlHttp=null;
  4.   if (window.ActiveXObject)
  5.     xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  6.   else
  7.     if (window.XMLHttpRequest)
  8.       xmlHttp = new XMLHttpRequest();
  9.   return xmlHttp;
  10.    }    
  11. }
  #12 (permalink)  
Antiguo 23/01/2014, 17:39
Avatar de Alexis88
Philosopher
 
Fecha de Ingreso: noviembre-2011
Ubicación: Tacna, Perú
Mensajes: 5.552
Antigüedad: 12 años, 5 meses
Puntos: 977
Respuesta: Convertir código a JQuery

Como tienes más de una instrucción por cada condición, es necesario que coloques las llaves de apertura y cerrado {}, si solamente fuera una instrucción, como en el ejemplo que te puse, las llaves no son necesarias, pero en tu caso, sí lo son. Fíjate en las variables que estás usando, estoy viendo que estás usando la que te puse de ejemplo y las tuyas al mismo tiempo, adecua el código, no lo copies literalmente.
__________________
«Juro por mi vida y mi amor por ella, que jamás viviré para el provecho de otro hombre, ni le pediré a otro hombre que viva para el mío».

Ayn Rand
  #13 (permalink)  
Antiguo 23/01/2014, 17:45
Avatar de satjaen  
Fecha de Ingreso: septiembre-2012
Ubicación: Jaén (Andalucía)
Mensajes: 893
Antigüedad: 11 años, 7 meses
Puntos: 10
Respuesta: Convertir código a JQuery

Cita:
Iniciado por Alexis88 Ver Mensaje
Como tienes más de una instrucción por cada condición, es necesario que coloques las llaves de apertura y cerrado {}, si solamente fuera una instrucción, como en el ejemplo que te puse, las llaves no son necesarias, pero en tu caso, sí lo son. Fíjate en las variables que estás usando, estoy viendo que estás usando la que te puse de ejemplo y las tuyas al mismo tiempo, adecua el código, no lo copies literalmente.
Pero con tu ejemplo tengo que poner todas las funciones como antes ?

  1. e.preventDefault();
  2. enviarFormulario();
  3. procesarEventos();
  4. crearXMLHttpRequest();
  #14 (permalink)  
Antiguo 23/01/2014, 18:05
Avatar de Alexis88
Philosopher
 
Fecha de Ingreso: noviembre-2011
Ubicación: Tacna, Perú
Mensajes: 5.552
Antigüedad: 12 años, 5 meses
Puntos: 977
Respuesta: Convertir código a JQuery

Si te fijas bien, el ejemplo que te puse es para cuando cambia el estado, es decir, cuando ocurre el evento onreadystatechange, por lo que lo único que tienes que adecuar, es lo que va adentro de la función dada para dicho evento, por eso te decía que los cambios que debes hacer, son básicamente en el bloque de código cuando readyState es igual a 4 y state, igual a 200. Cuando readyState es menor a 4, es cuando se muestra el Gif.
__________________
«Juro por mi vida y mi amor por ella, que jamás viviré para el provecho de otro hombre, ni le pediré a otro hombre que viva para el mío».

Ayn Rand
  #15 (permalink)  
Antiguo 24/01/2014, 02:27
Avatar de satjaen  
Fecha de Ingreso: septiembre-2012
Ubicación: Jaén (Andalucía)
Mensajes: 893
Antigüedad: 11 años, 7 meses
Puntos: 10
Respuesta: Convertir código a JQuery

Ok gracias Alexis:

Código Javascript:
Ver original
  1. function valida_envia(e)
  2. {
  3.    
  4.      var telefonos = document.forms['datos'].elements['telefonos'];
  5.     if (telefonos.value.length == 0)
  6.     {
  7.        
  8.         alert("Insertar el nº de teléfono");
  9.  
  10.         telefonos.focus();
  11.  
  12.         return 0;
  13.  
  14.     }
  15.     else
  16.     {
  17.   if (window.event)
  18.     window.event.returnValue=false;
  19.   else
  20.     if (e)
  21.       e.preventDefault();
  22.   enviarFormulario();
  23. }
  24.  
  25. var conexion1;
  26. function enviarFormulario()
  27. {
  28.   conexion1=crearXMLHttpRequest()
  29.   conexion1.onreadystatechange = function(){
  30.      
  31.     var salida = document.getElementById("carga")//El DIV
  32.        
  33.  
  34.     if (conexion1.readyState < 4)
  35.     {
  36.       $('#carga').css({
  37.                 opacity:1,
  38.                 display:'block'
  39.                
  40.             });
  41.          $('#fondo').css({
  42.                 opacity:.25
  43.             });
  44.          
  45.         salida.innerHTML = conexion1.responseText;
  46.        
  47.        
  48.     }else{
  49.    
  50.    
  51.    
  52.         setTimeout(function(){
  53.             var respuesta = conexion1.status == 200 ? conexion1.responseText : conexion1.status == 400 ? "La dirección brindada no existe" : "Error: " + conexion1.status;
  54.            
  55.             salida.innerHTML = respuesta;
  56.            
  57.             //////////////////////////////////////////////////////////////////////////////////////////contenido estado 4
  58.            
  59.               $('#fondo').css({
  60.                 opacity:1
  61.             });
  62.            
  63.            
  64.           $('#carga').css('display','none');
  65.         respuesta.innerHTML = conexion1.responseText;
  66.        
  67.    
  68.        
  69.          var xml = conexion1.responseXML;
  70.             dato=xml.getElementsByTagName("datos");
  71.             if(dato[0].firstChild.nodeValue=="1")
  72.             {
  73.                 num_user=xml.getElementsByTagName("numusuario");
  74.                
  75.                
  76.                 document.getElementById("movil").value =xml.getElementsByTagName("movil")[0].firstChild.nodeValue;
  77.                 document.getElementById("calle").value =xml.getElementsByTagName("calle")[0].firstChild.nodeValue;
  78.                 document.getElementById("dni").value =xml.getElementsByTagName("dni")[0].firstChild.nodeValue;
  79.                 document.getElementById("name").value =xml.getElementsByTagName("name")[0].firstChild.nodeValue;
  80.                 document.getElementById("edificio").value =xml.getElementsByTagName("edificio")[0].firstChild.nodeValue;
  81.                 document.getElementById("numero").value =xml.getElementsByTagName("numero")[0].firstChild.nodeValue;
  82.                 document.getElementById("puerta").value =xml.getElementsByTagName("puerta")[0].firstChild.nodeValue;
  83.                 document.getElementById("piso").value =xml.getElementsByTagName("piso")[0].firstChild.nodeValue;
  84.                 document.getElementById("letra").value =xml.getElementsByTagName("letra")[0].firstChild.nodeValue;
  85.                 document.getElementById("localidad").value =xml.getElementsByTagName("localidad")[0].firstChild.nodeValue;
  86.                 document.getElementById("provincia").value =xml.getElementsByTagName("provincia")[0].firstChild.nodeValue;
  87.                 document.getElementById("email").value =xml.getElementsByTagName("email")[0].firstChild.nodeValue;
  88.                
  89.            
  90.                  
  91.        
  92.             }else(dato[0].firstChild.nodeValue=="0")
  93.                  {                
  94.                      envia();
  95.                      
  96.                          }
  97.        
  98.    
  99.     //////////////////////////////////////////////////////////////////////////////////////////////////////fin contenido estado 4
  100.            
  101.         }, 2000);
  102.        
  103.    };
  104.    
  105.      }
  106.      
  107.   }
  108.   conexion1.open("GET", "val_telef.php?telefonos=" + telefonos.value, false);
  109.   conexion1.send(null);  
  110.  
  111.  
  112.     function crearXMLHttpRequest()
  113. {
  114.   var xmlHttp=null;
  115.   if (window.ActiveXObject)
  116.     xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  117.   else
  118.     if (window.XMLHttpRequest)
  119.       xmlHttp = new XMLHttpRequest();
  120.   return xmlHttp;
  121.    }   
  122. }

Entonces la única diferencia era meter la funcion setTimeout ?
Saludos

Última edición por satjaen; 24/01/2014 a las 02:45
  #16 (permalink)  
Antiguo 24/01/2014, 10:09
Avatar de Alexis88
Philosopher
 
Fecha de Ingreso: noviembre-2011
Ubicación: Tacna, Perú
Mensajes: 5.552
Antigüedad: 12 años, 5 meses
Puntos: 977
Respuesta: Convertir código a JQuery

Cita:
Iniciado por satjaen Ver Mensaje
Entonces la única diferencia era meter la funcion setTimeout ?
Así es.
__________________
«Juro por mi vida y mi amor por ella, que jamás viviré para el provecho de otro hombre, ni le pediré a otro hombre que viva para el mío».

Ayn Rand

Etiquetas: Ninguno
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:40.