Foros del Web » Programando para Internet » Jquery »

Exceptions en ajax events

Estas en el tema de Exceptions en ajax events en el foro de Jquery en Foros del Web. Hola estoy haciendo un plugin jquery sobre ajax level2 con reportes de errores mediante try catch mi inconveniente es el siguiente, en el plugin puedo ...
  #1 (permalink)  
Antiguo 18/03/2014, 00:46
Avatar de Ex_shadow  
Fecha de Ingreso: febrero-2012
Ubicación: Calera Avellaneda, Buenos Aires, Argentina, Argentina
Mensajes: 95
Antigüedad: 12 años, 1 mes
Puntos: 4
Pregunta Exceptions en ajax events

Hola estoy haciendo un plugin jquery sobre ajax level2 con reportes de errores mediante try catch mi inconveniente es el siguiente, en el plugin puedo elegir si mis datos van a ser normales o de forma json, el problema surge al obtener el error de su conversion posteo aquí el codigo y la linea en la que no puedo lograr que imprima o devuelva bien su exception

Plugin
Código Javascript:
Ver original
  1. (function($){
  2.    
  3.     // Constructor
  4.     $.AjaxPrepare = function(option){
  5.    
  6.         // Definiendo opciones
  7.         var options = $.extend($.AjaxPrepare.default,option);
  8.    
  9.         try{
  10.        
  11.             var ajax,
  12.                 dataPost,
  13.                 data = new Array();
  14.  
  15.             // Init
  16.             $.AjaxPrepare.init();
  17.  
  18.             // Parseo
  19.             $.AjaxPrepare.parse(options.method,options.insert);
  20.            
  21.             // Before
  22.             $.AjaxPrepare.before(options.onBefore);
  23.            
  24.             // Open
  25.             $.AjaxPrepare.open(options.method,options.url);
  26.            
  27.             // Estados
  28.             $.AjaxPrepare.status(options.type,options.onLoad,options.onLoaded);
  29.            
  30.             // Progreso
  31.             $.AjaxPrepare.progress(options.onProgress);
  32.            
  33.             // Envio final
  34.             $.AjaxPrepare.send(options.method);
  35.                    
  36.         }catch(e){
  37.        
  38.             if(typeof options.onError == 'function')
  39.                 options.onError(e);
  40.             else
  41.                 console.log(e);
  42.        
  43.         }
  44.    
  45.     }
  46.    
  47.     // Inicializador
  48.     $.AjaxPrepare.init = function(){
  49.    
  50.         // Ajax
  51.         if(window.XMLHttpRequest)
  52.             ajax = new XMLHttpRequest();
  53.        
  54.         else if(window.ActiveXObject)
  55.             ajax = new ActiveXObject("Microsoft.XMLHTTP");
  56.        
  57.         else
  58.             throw new Exception('[AjaxPrepare]','El objeto ajax no pudo ser inicializado.');
  59.        
  60.         // Formdata
  61.         if(window.FormData)
  62.             dataPost = new FormData();
  63.         else
  64.             throw new Exception('[AjaxPrepare]','El objeto formdata no pudo ser inicializado, no se podrán enviar archivos.');
  65.    
  66.     }
  67.    
  68.     // Parseo
  69.     $.AjaxPrepare.parse = function(method,datos){
  70.    
  71.         // POST
  72.         if(method=='post'){
  73.            
  74.             for(var i = 0; i < datos.length; i++){
  75.            
  76.                 dataPost.append(datos[i][0], datos[i][1]);
  77.            
  78.             }
  79.            
  80.         }else{
  81.        
  82.             data = new String('?');
  83.        
  84.             for(var i=0; i < datos.length; i++){
  85.            
  86.                 if(i<datos.length)
  87.                     data +=datos[i][0]+'='+datos[i][1]+'&';
  88.                 else
  89.                     data +=datos[i][0]+'='+datos[i][1];
  90.            
  91.             }
  92.        
  93.         }
  94.    
  95.     }
  96.        
  97.     // Before
  98.     $.AjaxPrepare.before = function(method){
  99.        
  100.         // Funcion previa
  101.         if(typeof method == 'function')
  102.             method();
  103.    
  104.     }
  105.        
  106.     // Open
  107.     $.AjaxPrepare.open = function(method,url){
  108.    
  109.         if(method=='post')
  110.             ajax.open(method,url,true);
  111.         else
  112.             ajax.open(method,url+data,true)
  113.        
  114.     }
  115.        
  116.     // Status
  117.     $.AjaxPrepare.status = function(type,onLoad,onLoaded){
  118.        
  119.         var report = 0;
  120.        
  121.         // Estados
  122.         ajax.onreadystatechange = function(){
  123.        
  124.             if(ajax.readyState==1 || ajax.readyState==2 || ajax.readyState==3){
  125.            
  126.                 onLoad();
  127.            
  128.             }
  129.            
  130.             if(ajax.readyState==4 && ajax.status==200){
  131.                
  132.                 // Si debe ser json
  133.                 if(type=='json'){
  134.                    
  135.                     // Si retorna un objeto
  136.                     if(typeof $.AjaxPrepare.JSON(ajax.response) == 'object'){
  137.                    
  138.                         onLoaded($.AjaxPrepare.JSON(ajax.response));
  139.                    
  140.                     // Si retorna una excepcion
  141.                     }else{
  142.                        
  143.                         throw new Exception("[AjaxPrepare]","No se pudieron obtener los datos correctamente. [JSON]");
  144.                    
  145.                     }
  146.                    
  147.                 }else{
  148.                    
  149.                     onLoaded(ajax.response);
  150.                
  151.                 }
  152.                    
  153.             }
  154.            
  155.             if(ajax.readyState==4 && ajax.status==404){
  156.                
  157.                 throw new Error('[AjaxPrepare]','No se pudo conectar a la pagina solicitada.');
  158.                
  159.             }
  160.        
  161.         };
  162.  
  163.     }
  164.        
  165.     // Json
  166.     $.AjaxPrepare.JSON = function(response){
  167.        
  168.         try{
  169.            
  170.             return JSON.parse(response);
  171.        
  172.         }catch(e){
  173.            
  174.             return false;
  175.        
  176.         }
  177.        
  178.     }
  179.        
  180.     // Progreso de peticion
  181.     $.AjaxPrepare.progress = function(onProgress){
  182.    
  183.         ajax.upload.onprogress = function(e){
  184.        
  185.             if(e.lengthComputable){
  186.            
  187.                 var porcentaje=Math.ceil((e.loaded/e.total)*100);
  188.            
  189.                 if(typeof onProgress=='function')
  190.                     onProgress(porcentaje);
  191.            
  192.             }
  193.        
  194.         };
  195.    
  196.     }
  197.        
  198.     // Send
  199.     $.AjaxPrepare.send = function(method){
  200.        
  201.         if(method=='post')
  202.             ajax.send(dataPost);
  203.         else
  204.             ajax.send(null);
  205.    
  206.     }
  207.    
  208.     // Exception
  209.     Exception = function(name,message){
  210.    
  211.         return {
  212.        
  213.              name: name,
  214.              message: message
  215.        
  216.         }
  217.    
  218.     }
  219.    
  220.  
  221.     // Opciones por default
  222.     $.AjaxPrepare.default = {
  223.  
  224.         insert      : [],                   // [ ['name',value],['name','value'] ] name: nombre con el que identificas desde php. value: valor que obtendras en php [string | int | file].
  225.         url         : String,               // Url php, etc... procesador de informacion. [String].
  226.         method      : String,               // Metodo a emplear para la peticion ['POST' | 'GET'].
  227.         type        : String,               // Type json, o normal
  228.  
  229.         onBefore    : function(){},         // onBefore(){}     Funcion antes del envio.
  230.         onLoad      : function(){},         // onLoad(){}       Funcion equivalente a readyState[1,2,3].
  231.         onLoaded    : function(response){}, // onLoaded(){}     Funcion equivalente a readyState[4] y Status[200].
  232.         onProgress  : function(progress){}, // onProgress(){}   Funcion que devuelve el procentaje de avance de la peticion.
  233.         onError     : function(){},         // onError(){}      Equivalente a readyState[4] y Status[404]
  234.  
  235.     }
  236. })(jQuery);

Forma de uso
Código Javascript:
Ver original
  1. $.AjaxPrepare({
  2.            
  3.             insert      : [['obtain','clientes'],['cantidad',40],['page',page]],
  4.             url         : BASE_URL+'fillClient/',
  5.             method      : 'post',              
  6.             type        : 'json',
  7.            
  8.             onBefore    : function(){
  9.            
  10.                 // Reportamos el progreso
  11.                 $('#listClientes layout.box-message[data-report-progress]').css('display','block');
  12.            
  13.             },         
  14.             //onLoad        : function(){},        
  15.             onLoaded    : function(response){
  16.                
  17.                 // Eliminamos el reporte de progreso
  18.                 $('#listClientes layout.box-message[data-report-progress]').css('display','none');
  19.                
  20.                 // Obtenemos los datos y los imprimimos
  21.                 structure(response);
  22.                
  23.             }, 
  24.             onProgress  : function(progress){},
  25.             onError     : function(e){
  26.                
  27.                 // Reporte de exceptions
  28.                 controlExeptions(e);                                //------------
  29.                    
  30.             },
  31.        
  32.         });


[ERROR]: el error que me devuelve es #object uncauht alguien que me ayude por favor ya hace dias que le estoy dando vueltas a este inconveniente, seria muy util!

LINEA DEL PROBLEMA 143

[Aclaracion] Funciona todo el plugin solo no recibo esa exception

Etiquetas: ajax, exception, javascript, try-catch
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 09:42.