pushState与ajax实现无刷新加载
一.JS代码:
$(document).ready(function() {
getContent();//初始化页面
$("nav a").click(function() {
var href = $(this).attr("href");
history.pushState("", "", href);//ajax可前进后退
getContent();//执行ajax
return false;//阻止默认事件
});
});
var getContent = function() {
hash = window.location.hash;
if (hash == "#/") { load_page("Home"); } else
if (hash == "#/blog") { load_page("Blog"); } else
if (hash == "#/productos") {load_page("Productos"); }
}
var load_page = function(inf){
$.ajax({
type: "GET",
url: "http://localhost:8080/test.php",
data: {page: inf},
cache: false,
success: function(result) {
$("#contenido").html(result);
}
});
}
window.onpopstate = function(event) {//点击前进后退时执行
getContent();
};
二.html代码
<nav> <a href="#/">Home</a> <a href="#/blog">blog</a> <a href="#/productos">productos</a> </nav> <section id="contenido" role="main"> </section>
三.test.php
<?php echo $_GET['page']; ?>

浙公网安备 33010602011771号