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

Ajax asincrono problemas con Internet explorer

Estas en el tema de Ajax asincrono problemas con Internet explorer en el foro de Frameworks JS en Foros del Web. Aupa estoy creando un script para hacer las peticiones ajax, el problema es que no me funciona de modo asincrono en internet explorer: @import url("http://static.forosdelweb.com/clientscript/vbulletin_css/geshi.css"); ...
  #1 (permalink)  
Antiguo 05/05/2009, 05:26
Avatar de ZiTAL  
Fecha de Ingreso: marzo-2004
Ubicación: Bermio (Bizkaia)
Mensajes: 1.545
Antigüedad: 20 años, 2 meses
Puntos: 62
Ajax asincrono problemas con Internet explorer

Aupa estoy creando un script para hacer las peticiones ajax, el problema es que no me funciona de modo asincrono en internet explorer:
Código javascript:
Ver original
  1. /**
  2.  * @author zital
  3.  *
  4.  * zajax: ajax library
  5.  * license: GPL 3.0
  6.  * version: 1.0.2
  7.  */
  8.  
  9. var zajax = function()
  10. {
  11.     this.page = window.location;                    // page to request the petition, default: the same page (window.location)
  12.     this.method = 'post';                           // ajax method: post or get, post by default
  13.     this.charset = 'utf-8';                         // charset utf-8 by default
  14.     this.response = '';                             // response method, XML, JSON or plain text, plain text by default
  15.     this.query;                                     // GET or POST query separated by & blank for default
  16.     this.async = true;                              // ajax connection method (asyncronous, syncronous), asyncronous by default
  17.     this.getSeparator = '?';                        // pagename and parameters separator ? by default
  18.  
  19.     // request public method
  20.     this.request = function()
  21.     {
  22.         var t = this;
  23.         var a = new xmlhttp();                      // get xmlhttp object
  24.         var b = setHeader(t.method, t.charset);     // set get/post different headers
  25.         setQuery(t);                                // construct get/post different properties
  26.         t.onRequest();                              // Method to do before all process
  27.         a.open(t.method, t.page, t.async);          // open ajax petition
  28.         a.setRequestHeader('Content-Type', b);      // set headers ALWAYS after OPEN
  29.         a.send(t.query);                            // send get/post query
  30.         getState(t, a);                             // ajax reponse state
  31.     };
  32.  
  33.     // public methods to redefine: w3schools.com
  34.     this.onRequest = function(){};                  // method to do before all process
  35.     this.onSetUp = function(){};                    // method to do when The request has been set up
  36.     this.onSend = function(){};                     // method to do when The request has been sent
  37.     this.onProcess = function(){};                  // method to do when The request is in process
  38.     this.onComplete = function(){};                 // method to do when The request is complete
  39.     this.onError = function(){};                    // method to do when The request return error
  40.  
  41.     // private method to set get/post headers
  42.     var setHeader = function(m, c)
  43.     {
  44.         var a = '';
  45.         if(m.toLowerCase()=='post')
  46.             a = a + "application/x-www-form-urlencoded;"; // post Header
  47.         a = a + "charset="+c;
  48.         return a;
  49.     };
  50.  
  51.     // private method set get/post petition properties
  52.     var setQuery = function(t)
  53.     {
  54.         // DEFAULT POST example page = index.php and query = a=hello, php -> $_POST['hello']
  55.         if(t.method!=='post')                       // GET example page = index.php?a=hello and query = '', php -> $_GET['hello']
  56.         {
  57.             t.page = t.page+t.getSeparator+t.query;
  58.             t.query = '';
  59.         }
  60.     };
  61.    
  62.     // private method to set ajax petition state
  63.     var getState = function(t, a)
  64.     {
  65.         if (t.async)
  66.             a.onreadystatechange = function()       // get petition changestates
  67.             {
  68.                 switch(a.readyState)
  69.                 {
  70.                     case 1:                         // if readystate is 1 The request has been set up
  71.                         t.onSetUp();
  72.                         break;
  73.                     case 2:                         // if readystate is 2 The request has been sent
  74.                         t.onSend();
  75.                         break;
  76.                     case 3:                         // if readystate is 3 The request is in process
  77.                         t.onProcess();
  78.                         break;
  79.                     case 4:                         // if readystate is 4 the request is complete
  80.                         reqResponse(t, a);
  81.                         break;
  82.                 }
  83.             };
  84.         else
  85.             reqResponse(t, a);
  86.     };
  87.    
  88.     // private method to get ajax petition response
  89.     var reqResponse = function(t, a)
  90.     {
  91.         if(a.status===200)                                  // if status is 200 petition OK    
  92.             if(t.response.toLowerCase()==='xml')            // XML response
  93.                 t.onComplete(a.responseXML);
  94.             else if(t.response.toLowerCase()==='json')      // JSON response
  95.                 t.onComplete(eval("("+t.responseText+")"));
  96.             else                                            // plain text response
  97.                 t.onComplete(t.responseText);
  98.         else
  99.             t.onError();                                    // if error occurred execute error method
  100.     };
  101.    
  102.     // private method get xmlhttp object
  103.     var xmlhttp = function()
  104.     {
  105.         var a;try{a = new XMLHttpRequest();}
  106.         catch(e){try{a = new ActiveXObject('Msxml2.XMLHTTP');}
  107.         catch(e){try{a = new ActiveXObject('Microsoft.XMLHTTP');}
  108.         catch(e){alert("Your browser doesn't support ajax");return false}
  109.         }}return a;
  110.     };
  111. };

el problema es que no entra en:
Código javascript:
Ver original
  1. a.onreadystatechange = function()

y no me da ningún error:

código HTML
Código html:
Ver original
  1. var a = new zajax();
  2.     a.async = true;
  3.     a.onComplete = function()
  4.     {
  5.         alert('yeah!!');
  6.     };
  7.     a.request();

Muchas gracias, eskerrik asko :)
__________________
http://zital.no-ip.org
____________________

Euskerie ahuen eta bijotzan
  #2 (permalink)  
Antiguo 05/05/2009, 06:44
venkman
Invitado
 
Mensajes: n/a
Puntos:
Respuesta: Ajax asincrono problemas con Internet explorer

Una cuestión? Estás haciendo pruebas en local o en algún servidor muy "cercano" (cercano en la red, se entiende)?

Lo digo porque una posibilidad es que para cuando asignas la función a a.onreadystatechange, la petición ya haya terminado y readystatechange no vuelva a cambiar. Y es una posibilidad porque, según veo, estás haciendo la llamada primero y después asignando el manejador.

Podrías probar a asignar el manejador de onreadystatechange antes de hacer el a.send(t.query). De hecho, sea o no esto el origen de tu problema, deberías hacerlo de todos modos.
  #3 (permalink)  
Antiguo 05/05/2009, 06:48
Avatar de ZiTAL  
Fecha de Ingreso: marzo-2004
Ubicación: Bermio (Bizkaia)
Mensajes: 1.545
Antigüedad: 20 años, 2 meses
Puntos: 62
Respuesta: Ajax asincrono problemas con Internet explorer

tienes razón cambiando:
Código javascript:
Ver original
  1. a.send(t.query);                            // send get/post query
  2.         getState(t, a);                             // ajax reponse state

por:
Código javascript:
Ver original
  1. getState(t, a);                             // ajax reponse state
  2.         a.send(t.query);                            // send get/post query

funciona a la perfección, muchas gracias eskerrik asko :)
__________________
http://zital.no-ip.org
____________________

Euskerie ahuen eta bijotzan
  #4 (permalink)  
Antiguo 05/05/2009, 07:59
venkman
Invitado
 
Mensajes: n/a
Puntos:
Respuesta: Ajax asincrono problemas con Internet explorer

Lo único malo de eso, es que no te va a servir para cuando la llamada sea síncrona.

Creo que deberías separar más ambos casos, hacerlos más independientes. En un caso deberás asignar el manejador antes de llamar, como hemos visto, y en el otro tendrás que obtener el resultado como lo hacías antes. Porque ahora, en el caso de las llamadas síncronas estás intentando obtener la respuesta ( reqResponse(t, a) ) antes de haber llamado.
  #5 (permalink)  
Antiguo 05/05/2009, 08:08
Avatar de ZiTAL  
Fecha de Ingreso: marzo-2004
Ubicación: Bermio (Bizkaia)
Mensajes: 1.545
Antigüedad: 20 años, 2 meses
Puntos: 62
Respuesta: Ajax asincrono problemas con Internet explorer

Entonces quedaría algo como:
Código javascript:
Ver original
  1. ...
  2. ...
  3.     // request public method
  4.     this.request = function()
  5.     {
  6.         var t = this;
  7.         var a = new xmlhttp();                      // get xmlhttp object
  8.         var b = setHeader(t.method, t.charset);     // set get/post different headers
  9.         setQuery(t);                                // construct get/post different properties
  10.         t.onRequest();                              // Method to do before all process
  11.         a.open(t.method, t.page, t.async);          // open ajax petition
  12.         a.setRequestHeader('Content-Type', b);      // set headers ALWAYS after OPEN
  13.         getState(t, a);                             // ajax reponse state
  14.     };
  15. ...
  16. ...
  17. ...
  18.     // private method to set ajax petition state
  19.     var getState = function(t, a)
  20.     {
  21.         if(t.async)
  22.         {
  23.             a.onreadystatechange = function() // get petition changestates
  24.             {
  25.                 switch (a.readyState) {
  26.                     case 1: // if readystate is 1 The request has been set up
  27.                         t.onSetUp();
  28.                         break;
  29.                     case 2: // if readystate is 2 The request has been sent
  30.                         t.onSend();
  31.                         break;
  32.                     case 3: // if readystate is 3 The request is in process
  33.                         t.onProcess();
  34.                         break;
  35.                     case 4: // if readystate is 4 the request is complete
  36.                         reqResponse(t, a);
  37.                         break;
  38.                 }
  39.             };
  40.             a.send(t.query);                                // send get/post query     
  41.         }
  42.         else
  43.         {
  44.             a.send(t.query);                                // send get/post query     
  45.             reqResponse(t, a);
  46.         }
  47.     };
  48. ...
  49. ...
__________________
http://zital.no-ip.org
____________________

Euskerie ahuen eta bijotzan
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 14:10.