pushState
不发出请求,它只是更改网址并存储新的历史记录条目。思考这个概念,不可能刷新或书签,因为服务器总是会提出请求。需要服务器端解决方案。
几个小时搜索后,我找到了解决办法,每一个呼叫必须被重定向到index.php
让PHP处理请求。历史API,刷新和书签
rewrite ^/(.*)$ /index.php?page=$1 last
我不知道这个文件应该究竟如何可以让一个网站刷新或书签的页面。有人能帮助我吗?我举了一个例子来帮助澄清。
的index.html
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>History API</title>
<script>
function ajax (url, callback) {
var conection = new XMLHttpRequest();
conection.open ("GET", url, true);
conection.setRequestHeader ("X-Requested-With", "XMLHttpRequest");
conection.send (null);
conection.onreadystatechange = function() {
if (conection.readyState === 4) {
if (conection.status === 200) {
callback (conection.responseText);
}
else if (conection.status === 404) {
alert ("Page not found !");
}
else {
alert ("Error !");
}
}
}
}
window.addEventListener ("popstate", function (event) {
var state = event.state;
if (state) {
document.getElementById ("content").innerHTML = state["content"];
}
});
document.addEventListener ("DOMContentLoaded", function() {
var content = document.getElementById ("content");
var menu = document.getElementById ("menu");
menu.addEventListener ("click", function (event) {
var target = event.target;
if (target.nodeName === "A") {
ajax (target.href, function (result) {
history.pushState ({"content": result}, target.innerHTML, target.href);
content.innerHTML = result;
});
event.preventDefault();
}
});
});
</script>
<style>
body {
width: 400px;
}
div {
border: 1px solid black;
padding: 10px;
}
</style>
</head>
<body>
<div id = "menu">
<a href = "page1.html">Page 1</a>
<a href = "page2.html">Page 2</a>
</div>
<div id = "content"></div>
</body>
</html>
的index.php
<?php
isset ($_GET["page"]) or exit ("Error !");
$page = $_GET["page"];
// Ajax request
if (isset ($_SERVER["HTTP_X_REQUESTED_WITH"]) && strtolower ($_SERVER["HTTP_X_REQUESTED_WITH"]) === "xmlhttprequest") {
if (file_exists ($page)) {
require_once ($page);
}
else {
header ("HTTP/1.1 404 Not Found");
}
}
else {
require_once ("index.html");
}
?>
page1.html
你好,我是第1页。很高兴见到你。
page2.html
哥哥你好。我第2
点击(OK)
刷新(失败)
你说安全的重要事情,谢谢。尽快我会照顾他们。 – Caio 2012-07-24 22:00:57
嘿男人!你的回答真的帮了我,我的问题解决了。谢谢 ! – Caio 2012-07-26 13:15:51