2016-01-13 86 views
0

我的網站使用腳本來瀏覽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); 
      } 
     } 

    }); 

} 
+0

呃...有點像''? –

+0

然後,您需要通過將'location.hash'的值發送到PHP來更改您的腳本以發送AJAX查詢。檢查我的答案。 –

回答

1

將目錄添加到URL,就可以使用history API。要添加一個新的目錄,或改變#部分:現在

var state = { 'page_id': 1, 'user_id': 5 }; // This is totally irrelevant. 
var title = 'Hello World';     // Some title/ 
var url = '#conditions/cookies';   // The main URL. 

history.pushState(state, title, url); 

而且,在你的AJAX調用,通過發送發送#hash值:

data: location.hash       // This sends condition/cookies to PHP. 

所以構建AJAX會是這樣的:

$.post("page.php", page: location.hash.substring(1)), function() { 
    history.pushState(null, '', '#conditions/cookies'); 
}); 
+0

非常有趣。這將如何工作?把它放在ajax文件中? – Mia

+0

'location.hash'將在'http:// example.com /#conditions/cookies'中包含'「#conditions/cookies」'。試試看。 –

+0

@Mia用完整的示例檢查更新的答案,並告訴我它是否有幫助? –