Foro de elhacker.net

Programación => Desarrollo Web => Mensaje iniciado por: WarGhost en 28 Mayo 2012, 07:04 am



Título: Plugin JS para web modular con AJAX.
Publicado por: WarGhost en 28 Mayo 2012, 07:04 am
Os dejo aquí un código que usaba hace algún tiempo para poder gestionar una web modular desde AJAX, la verdad deje de usuario por que como mucho ya saben AJAX y Google ademas de incontables problemas con los estándares de accesibilidad.

De todos modos es divertido y para aplicaciones propias es muy interesante.

Primero que nada necesitamos dos Plugins:

  • jquery (https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js)
  • jquery.history (http://github.com/tkyk/jquery-history-plugin/raw/master/jquery.history.js)

Aquí el código XHTML para cargar la web modular:

Código:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
       
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
        <script src="js/basic.js" type="text/javascript"></script>
        <script src="js/jquery.history.js" type="text/javascript"></script>

<title>Web Modular.</title>
    </head>

    <body>
        <div id="mainPage">
            <div id="wrapper-xmlHttpRequest">
            </div>
        </div> 
    <body>
</html>

Y aquí el código JS que representaría basic.js:
Código:
goes=true;

function ajaxLoad(address, title, variable, top) {
$("#wrapper-xmlHttpRequest").load("mainfile.php?page=" + address + variable, function() {
if(title!=""){document.title = "Tu sitio web - " + title;}
if(goes==true){
goes=false;
if(top==true){
var b=$("html").offset();
var a=b.top;

$("html, body").animate({scrollTop:a},500, function() {goes=true;});
}
}
});
}

$(document).ready(function(){
$.history.init(function(url) {
var page = location.hash.replace("#","").split("/");

if(page[1]==undefined){
location.hash="#/home/"
} else{
switch(page[1].toLowerCase()){
case "home":
ajaxLoad("home","Portada","", true);
break;
default:
location.hash="#/error/404/";
}
}
});
})

Para añadir un modulo solo tienes que añadir un nuevo case y utilizar la función ajaxLoad, dicha
Citar
funcion tiene 4 argumentos:
address - "dirección del modulo en el fichero php"
title - "titulo de la pagina"
variable - "argumentos que quieras enviar"
top - "si pones true la pagina se eleva hasta arriba, sino se queda como esta."

Como os digo, no recomiendo mucho su uso pq da conflictos con SEO, SEM, Open graph etc... pero si estas en un proyecto pequeño y quieres probar el potencial de ajax viene muy bien.

Espero haber podido ayudar!
Un saludo