Código Javascript:
Ver original
(function($){ $.AjaxPrepare = function(options){ var settings = jQuery.extend({ // Propiedades url : '', response : 'text', method : 'POST', crossDomain : false, insert : [], // Metodos onProgress : function(){}, onBefore : function(){}, onLoaded : function(){}, onError : function(){}, },options); try{ // Creamos nuestro xhr var ajax = createXHR(settings.crossDomain); // Preparamos objeto a enviar var datos = prepareInsert(settings.method,settings.insert); // Antes de enviar onBefore(settings.onBefore); // Open open(ajax,settings.method,settings.url,datos); // Progress onProgress(ajax,settings.onProgress); // Finalizado onLoaded(ajax,settings.response,settings.onLoaded); // Envio sendRequest(ajax,settings.method,datos); }catch(e){ // Error settings.onError(e); } } // ----- Errores ------ error = { 1: { name: '[ErrorCode: 1]', message: 'Surgio un error al obtener sus datos JSON.' } } // ----- Metodos ------ onBefore = function(functions){ if(typeof functions == "function") functions(); } createXHR = function(domain){ if(domain == true && "withCredentials" in XMLHttpRequest) var xhr = new XMLHttpRequest(); else if(domain==true && !"withCredentials" in XMLHttpRequest) var xhr = new XDomainRequest() else var xhr = new XMLHttpRequest(); return xhr; } prepareInsert = function(method,datos){ // POST if(method.toLowerCase() =='post'){ var data = new FormData; for(var i = 0; i < datos.length; i++){ data.append(datos[i][0], datos[i][1]); } }else{ var data = new String('?'); for(var i=0; i < datos.length; i++){ if(i <datos.length) data += datos[i][0]+'='+datos[i][1]+'&'; else data += datos[i][0]+'='+datos[i][1]; } } return data; } open = function(ajax,method,url,data){ if(method.toLowerCase()=='post') ajax.open(method,url,true); else ajax.open(method,url+data,true); } onProgress = function(ajax,functions){ if(typeof functions == "function") ajax.upload.onprogress = function(e){ if(e.lengthComputable){ var porcentaje=Math.ceil((e.loaded/e.total)*100); functions(porcentaje); } }; } onLoaded = function(ajax,response,functions){ if(response.toLowerCase()=='json') if(typeof JSON.parse(ajax.response) =='object') ajax.onload = function(){ functions(JSON.parse(ajax.response)); } else throw Error(error[1]); else ajax.onload = functions(ajax.response); } sendRequest = function(ajax,method,datos){ if(method.toLowerCase()=='post'){ ajax.send(datos); }else{ ajax.send(null); } } })(jQuery);
Se llama asi
Código HTML:
Ver original
<!doctype html> <head> </head> <body> <div class="container"> </div> <script type="text/javascript"> function prueba(){ $.AjaxPrepare({ url: 'prueba.php', response: 'text', method: 'post', onBefore: function(){ // Procesando $('#output').html('Cargando...'); }, onLoaded: function(response){ // Mostrando $('#output').html(response); }, onError: function(e){ alert(e); } }); } $(document).ready(function(){ prueba(); }); </script> </body>
El archivo php
Código PHP:
Ver original
<?php echo 'hola'; ?>