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

Creando un plugin jquery XHR2

Estas en el tema de Creando un plugin jquery XHR2 en el foro de Frameworks JS en Foros del Web. Hola estaba creando 2 plugins jquery sobre XHR level 2. Primero explicare el fin de cada uno. El primero: $.AjaxPrepare es casi igual que $.ajax ...
  #1 (permalink)  
Antiguo 28/02/2013, 23:44
 
Fecha de Ingreso: septiembre-2012
Ubicación: Buenos aires
Mensajes: 110
Antigüedad: 11 años, 6 meses
Puntos: 9
Pregunta Creando un plugin jquery XHR2

Hola estaba creando 2 plugins jquery sobre XHR level 2.

Primero explicare el fin de cada uno.

El primero:

$.AjaxPrepare es casi igual que $.ajax de jquery, con la diferencia que este usa todo lo que es xhr level 2 por ende solo los actuales navegadores los usan , este que cree incorpora la posibilidad de agregar archivos a las peticiones ajax uploads, y también barras de progreso en el mismo. lo cual es genial.

[Este primero funciona perfectamente solo me tira un error cuando lo convino con el segundo aqui a continuacion]

$.ImagePreview por fin después de buscar por mucho tiempo y no encontrar una solucion linda, hicieron el milagro en xhr2 de incorporar fileReader con el cual hice un muy pequeño pero efectivo y sencillo plugin.

[Cuando convino este con el anterior surge el problema]

Razon para usar xhr2:
[Me encontre con clientes que quieren obviamente sus paginas compatibles con todos los navegadores , pero no asi, los administradores, les da igual, a lo que me pregunte, si uso todo lo de la edad de piedra para los usuarios que visitan y lo nuevo para los admins?]



Aclaracion : Los 2 plugins en convinacion funcionan, solo que en el console log de chrome [no probe en los demás aun..] me salta esto:

Uncaught TypeError: Object #<Object> has no method 'onLoaded'



Aqui los plugis:


$.AjaxPrepare
Código Javascript:
Ver original
  1. (function($){
  2.    
  3.    
  4.     $.AjaxPrepare = function(option){
  5.        
  6.         // Definiendo opciones
  7.         options = $.extend($.AjaxPrepare.default,option);
  8.        
  9.         // Instanciando
  10.         var ajax    = new XMLHttpRequest();
  11.         var form    = new FormData();
  12.        
  13.         // Condicionales
  14.         var swiTch  = false;
  15.         var GET     = null;
  16.        
  17.         // Definiendo metodo
  18.         if(options.method=='' || !options.method){
  19.            
  20.             options.method='POST';
  21.            
  22.         }
  23.        
  24.         // Insertando datos pasados por post.
  25.         if(options.insert.length>0 && options.method=='POST'){
  26.            
  27.             for(var i=0;i<options.insert.length;i++){
  28.                
  29.                 form.append(options.insert[i][0],options.insert[i][1]);
  30.                
  31.             }
  32.            
  33.         }
  34.        
  35.         // Parseando datos ingresados por get.
  36.         if(options.insert.length>0 && options.method=='GET'){
  37.            
  38.             GET='?';
  39.            
  40.             for(var i=0;i<options.insert.length;i++){
  41.                
  42.                 GET += options.insert[i][0]+'='+options.insert[i][1];
  43.                
  44.                 if((i+1)!==options.insert.length){
  45.                    
  46.                     GET+='&';
  47.                
  48.                 }
  49.             }
  50.             swiTch=true;
  51.         }
  52.        
  53.         // Definiendo forma de abrir
  54.         if(swiTch && GET!==null){
  55.            
  56.             ajax.open(options.method,options.url+GET,true);
  57.        
  58.         }else{
  59.            
  60.             ajax.open(options.method,options.url,true);
  61.            
  62.         }
  63.        
  64.         // Estados
  65.         ajax.onreadystatechange = function(){
  66.            
  67.             if(ajax.readyState==1 || ajax.readyState==2 || ajax.readyState==3){
  68.                
  69.                 options.onLoad();
  70.                
  71.             }
  72.            
  73.             if(ajax.readyState==4 && ajax.status==200){
  74.                
  75.                 options.onLoaded(ajax.response);
  76.                
  77.             }
  78.            
  79.             if(ajax.readyState==4 && ajax.status==404){
  80.                
  81.                 options.onError();
  82.            
  83.             }
  84.        
  85.         };
  86.        
  87.         // Progreso de peticion
  88.         ajax.upload.onprogress = function(e){
  89.            
  90.             if(e.lengthComputable){
  91.                
  92.                 var porcentaje=Math.ceil((e.loaded/e.total)*100);
  93.                
  94.                 options.onProgress(porcentaje);
  95.            
  96.             }
  97.            
  98.         };
  99.        
  100.         // Forma de envio
  101.         if(swiTch && GET!==null){
  102.            
  103.             ajax.send(null);
  104.            
  105.         }else{
  106.            
  107.             ajax.send(form);
  108.            
  109.         }
  110.        
  111.     }
  112.    
  113.     // Opciones por default
  114.     $.AjaxPrepare.default = {
  115.        
  116.         insert      : [],                   // [ ['name',value],['name','value'] ] name: nombre con el que identificas desde php. value: valor que obtendras en php [string | int | file].
  117.         url         : String,               // Url php, etc... procesador de informacion. [String].
  118.         method      : String,               // Metodo a emplear para la peticion ['POST' | 'GET'].
  119.  
  120.         onLoad      : function(){},         // onLoad(){}       Funcion equivalente a readyState[1,2,3].
  121.         onLoaded    : function(response){}, // onLoaded(){}     Funcion equivalente a readyState[4] y Status[200].
  122.         onProgress  : function(progress){}, // onProgress(){}   Funcion que devuelve el procentaje de avance de la peticion.
  123.         onError     : function(){},         // onError(){}      Equivalente a readyState[4] y Status[404]
  124.        
  125.     }
  126.    
  127.    
  128.    
  129. })(jQuery);


$.ImagePreview

Código Javascript:
Ver original
  1. (function($){
  2.  
  3.     $.ImagePreview = function(option){
  4.        
  5.         // Definiendo opciones
  6.         options = $.extend($.ImagePreview.default,option);
  7.        
  8.         // Instanciando
  9.         var reader = new FileReader();
  10.        
  11.         // onLoad
  12.         reader.onload = function(e){
  13.            
  14.             options.onLoad(e.target.result);
  15.        
  16.         };
  17.        
  18.         switch(options.type){
  19.            
  20.             case 'Binary'       : result = reader.readAsBinaryString(options.file); break;
  21.             case 'Text'         : result = reader.readAsText(options.file); break;
  22.             case 'Url'          : result = reader.readAsDataURL(options.file); break;
  23.             case 'ArrayBuffer'  : result = reader.readAsArrayBuffer(options.file); break;
  24.  
  25.             default             : result = reader.readAsDataURL(options.file); break;
  26.         }
  27.  
  28.  
  29.        
  30.         result;
  31.        
  32.     }
  33.    
  34.     // Opciones por default
  35.     $.ImagePreview.default = {
  36.        
  37.         file        : document,             // document.getElementById('file').files[n];
  38.         type        : '',                   //  Binary = [readAsBinaryString] || Text = [readAsText] || Url = [readAsDataURL] || ArrayBuffer = [readAsArrayBuffer]
  39.         onLoad      : function(image){},    // onLoad(){}   Funcion que devuelve la imagen en el por default en dataUrl.
  40.        
  41.     }
  42.  
  43. })(jQuery);


Forma de uso:

Código Javascript:
Ver original
  1. $(document).ready(function(e) {
  2.    
  3.     $('#button').click(function(){
  4.        
  5.         $.AjaxPrepare({
  6.            
  7.             insert  : [['saludo','hola'],['despido','chau']],
  8.             url     : '../Pruebas/Process.php',
  9.             method  : 'GET',
  10.            
  11.             onLoad  : function(){
  12.                
  13.                 $.ImagePreview({
  14.                    
  15.                     file    : document.getElementById('files').files[0],
  16.                     type    : 'Url',
  17.                     onLoad  : function(result){
  18.                        
  19.                         $('#thumb').attr('src',result);
  20.                        
  21.                     }
  22.                    
  23.                 });
  24.                
  25.                 alert('Cargando...');
  26.                
  27.             },
  28.             onLoaded: function(response){
  29.                
  30.                 alert(response);
  31.                
  32.             },
  33.             onError : function(){
  34.                
  35.                 alert('ups sucedio algo mal :/');
  36.                
  37.             }
  38.            
  39.         });
  40.        
  41.     });
  42.    
  43. });

html
Código HTML:
Ver original
  1. <input type="file" id="files" multiple="multiple"/>
  2.  
  3. <input type="button" id="button" value="prueba" />
  4.  
  5. <aside id="Content">
  6.  
  7. <img src="" id="thumb" />
  8.  

Última edición por underwebinfo; 28/02/2013 a las 23:53

Etiquetas: javascript, jquery, plugin
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 17:58.