我的網站使用腳本來瀏覽AJAX頁面。主頁的網址是這樣的:http://example.com/#home
,實際主頁位於pages/page_home.php
。在哈希中添加目錄AJAX
如何在散列中添加目錄?這是我的代碼。
<?php
if(!$_POST['page']) die("0");
$page = $_POST['page'];
if(file_exists('pages/page_'.$page.'.php'))
echo file_get_contents('pages/page_'.$page.'.php');
else echo '<div class="box">404 - That page could not be found. <a href="#home">Click here</a> to return.</div>';
?>
我的動機這樣做是爲了使條件頁面,以便當訪問者點擊了/#conditions
網址更改/#conditions/cookies
餅乾鏈接是整潔的。
編輯:全碼
var state = { 'page_id': 1, 'user_id': 5 };
var title = 'Hello World';
var url = '#conditions/cookies';
history.pushState(state, title, url);
var default_content="";
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
options.async = true;
});
$(document).ready(function(){
checkURL();
$('ul li a').click(function (e){
checkURL(this.hash);
});
//filling in the default content
default_content = $('#pageContent').html();
setInterval("checkURL()",250);
});
var lasturl="";
function checkURL(hash)
{
if(!hash) hash=window.location.hash;
if(hash != lasturl)
{
lasturl=hash;
// FIX - if we've used the history buttons to return to the homepage,
// fill the pageContent with the default_content
if(hash=="")
$('#pageContent').html(default_content);
else
loadPage(hash);
}
}
function loadPage(url) {
url=url.replace('#','');
$.post("load_page.php", page: location.hash.substring(1)), function() {
history.pushState(null, '', '#conditions/cookies');
});
$.ajax({
type: "POST",
url: "load_page.php",
data: location.hash,
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0) {
$('#pageContent').html(msg);
}
}
});
}
呃...有點像''? –
@PraveenKumar我知道,但腳本不是爲此而生。它目前只支持像'/#conditions'這樣的鏈接,而不是'/#conditions/cookies'。 – Mia
然後,您需要通過將'location.hash'的值發送到PHP來更改您的腳本以發送AJAX查詢。檢查我的答案。 –