dt614037527
dt614037527
2015-12-15 20:25

AJAX页面 - 如何使用#home等

I'm trying to make AJAX pages using the post from Tutorialzine.

This script makes pages appear using AJAX. The problem is that the script works with numbers, example: http://example.com/#page1, http://example.com/#page2 etc..

How to make this script so it doesn't need the #page1 or #page2 in the URL, but #home etc..

Sorry if I explained this wrong, English isn't my native language and it's hard for me to explain.

index.html

<script type="text/javascript" src="script.js"></script>
<ul id="navigation">
<li><a href="#page1">Page 1</a></li>
<li><a href="#page2">Page 2</a></li>
<li><a href="#page3">Page 3</a></li>
<li><a href="#page4">Page 4</a></li>
<li><img id="loading" src="img/ajax_load.gif" alt="loading" /></li>
</ul>

<div id="pageContent"></div>

script.js

var default_content="";

$(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('#page','');

    $('#loading').css('visibility','visible');

    $.ajax({
        type: "POST",
        url: "load_page.php",
        data: 'page='+url,
        dataType: "html",
        success: function(msg){

            if(parseInt(msg)!=0)
            {
                $('#pageContent').html(msg);
                $('#loading').css('visibility','hidden');
            }
        }

    });

}

load_page.php

<?php

if(!$_POST['page']) die("0");

$page = (int)$_POST['page'];

if(file_exists('pages/page_'.$page.'.html'))
echo file_get_contents('pages/page_'.$page.'.html');

else echo 'There is no such page!';
?>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • doujupa7567 doujupa7567 6年前

    You have to do 4 small changes

    1) instead url=url.replace('#page',''); use url=url.replace('#',''); so the output in case of #page1 will be page1 or #home -> home pas that url to ajax in same way as it now and make ajax to your load_page.php

    2) rename all your page_1.html html files to pages/page_home.html

    3) change your <a href="#page1">Page 1</a> links to <a href="#home">Page 1</a>

    4) change $page = (int)$_POST['page']; in load_page.php to $page = $_POST['page'];

    so it mean according to your hash #some_name you should have page_some_name.html

    点赞 评论 复制链接分享

为你推荐