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(function($){
$.AjaxPrepare = function(option){
// Definiendo opciones
options = $.extend($.AjaxPrepare.default,option);
// Instanciando
var ajax = new XMLHttpRequest();
var form = new FormData();
// Condicionales
var swiTch = false;
var GET = null;
// Definiendo metodo
if(options.method=='' || !options.method){
options.method='POST';
}
// Insertando datos pasados por post.
if(options.insert.length>0 && options.method=='POST'){
for(var i=0;i<options.insert.length;i++){
form.append(options.insert[i][0],options.insert[i][1]);
}
}
// Parseando datos ingresados por get.
if(options.insert.length>0 && options.method=='GET'){
GET='?';
for(var i=0;i<options.insert.length;i++){
GET += options.insert[i][0]+'='+options.insert[i][1];
if((i+1)!==options.insert.length){
GET+='&';
}
}
swiTch=true;
}
// Definiendo forma de abrir
if(swiTch && GET!==null){
ajax.open(options.method,options.url+GET,true);
}else{
ajax.open(options.method,options.url,true);
}
// Estados
ajax.onreadystatechange = function(){
if(ajax.readyState==1 || ajax.readyState==2 || ajax.readyState==3){
options.onLoad();
}
if(ajax.readyState==4 && ajax.status==200){
options.onLoaded(ajax.response);
}
if(ajax.readyState==4 && ajax.status==404){
options.onError();
}
};
// Progreso de peticion
ajax.upload.onprogress = function(e){
if(e.lengthComputable){
var porcentaje=Math.ceil((e.loaded/e.total)*100);
options.onProgress(porcentaje);
}
};
// Forma de envio
if(swiTch && GET!==null){
ajax.send(null);
}else{
ajax.send(form);
}
}
// Opciones por default
$.AjaxPrepare.default = {
insert : [], // [ ['name',value],['name','value'] ] name: nombre con el que identificas desde php. value: valor que obtendras en php [string | int | file].
url : String, // Url php, etc... procesador de informacion. [String].
method : String, // Metodo a emplear para la peticion ['POST' | 'GET'].
onLoad : function(){}, // onLoad(){} Funcion equivalente a readyState[1,2,3].
onLoaded : function(response){}, // onLoaded(){} Funcion equivalente a readyState[4] y Status[200].
onProgress : function(progress){}, // onProgress(){} Funcion que devuelve el procentaje de avance de la peticion.
onError : function(){}, // onError(){} Equivalente a readyState[4] y Status[404]
}
})(jQuery);
$.ImagePreview
Código Javascript
:
Ver original(function($){
$.ImagePreview = function(option){
// Definiendo opciones
options = $.extend($.ImagePreview.default,option);
// Instanciando
var reader = new FileReader();
// onLoad
reader.onload = function(e){
options.onLoad(e.target.result);
};
switch(options.type){
case 'Binary' : result = reader.readAsBinaryString(options.file); break;
case 'Text' : result = reader.readAsText(options.file); break;
case 'Url' : result = reader.readAsDataURL(options.file); break;
case 'ArrayBuffer' : result = reader.readAsArrayBuffer(options.file); break;
default : result = reader.readAsDataURL(options.file); break;
}
result;
}
// Opciones por default
$.ImagePreview.default = {
file : document, // document.getElementById('file').files[n];
type : '', // Binary = [readAsBinaryString] || Text = [readAsText] || Url = [readAsDataURL] || ArrayBuffer = [readAsArrayBuffer]
onLoad : function(image){}, // onLoad(){} Funcion que devuelve la imagen en el por default en dataUrl.
}
})(jQuery);
Forma de uso:
Código Javascript
:
Ver original$(document).ready(function(e) {
$('#button').click(function(){
$.AjaxPrepare({
insert : [['saludo','hola'],['despido','chau']],
url : '../Pruebas/Process.php',
method : 'GET',
onLoad : function(){
$.ImagePreview({
file : document.getElementById('files').files[0],
type : 'Url',
onLoad : function(result){
$('#thumb').attr('src',result);
}
});
alert('Cargando...');
},
onLoaded: function(response){
alert(response);
},
onError : function(){
alert('ups sucedio algo mal :/');
}
});
});
});
html
Código HTML:
Ver original<input type="file" id="files" multiple="multiple"/>
<input type="button" id="button" value="prueba" />
<img src="" id="thumb" />