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