2016-01-13 84 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用完整的示例检查更新的答案,并告诉我它是否有帮助? –