在哈希AJAX中添加目录

时间:2016-01-13 13:55:51

标签: javascript php jquery ajax

我的网站使用脚本在AJAX中浏览页面。主页网址例如:http://example.com/#home,实际主页位于pages/page_home.php

如何在哈希中添加目录?这是我的代码。

<?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中的Cookie链接时,网址会更改为/#conditions/cookies更整洁。< / p>

编辑:完整代码

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);
            }
        }

    });

}

1 个答案:

答案 0 :(得分:0)

要向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');
});