2015-12-15 46 views
0

我正在嘗試使用post from Tutorialzine製作AJAX頁面。AJAX頁面 - 如何使用#home等

此腳本使頁面顯示使用AJAX。問題是,該腳本可與數字,例如:http://example.com/#page1http://example.com/#page2等。

如何使這個腳本,因此不需要#page1或URL #page2,但#home等。

對不起,如果我解釋了這個錯誤,英語不是我的母語,我很難解釋。

的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!'; 
?> 

回答

0

你要做4個小的變化

1),而不是url=url.replace('#page','');使用url=url.replace('#','');所以在#page1情況下輸出將page1#home - >home PAS是url以同樣的方式阿賈克斯現在和讓AJAX你load_page.php

2)所有page_1.html HTML文件重命名爲pages/page_home.html

3)改變你的<a href="#page1">Page 1</a>鏈接到load_page.php<a href="#home">Page 1</a>

4)改變$page = (int)$_POST['page'];$page = $_POST['page'];

所以根據您的哈希#some_name你應該意味着page_some_name.html

+0

我會努力的! BRB! – bemyhero

+0

我不能讓它工作,我可能做錯了什麼?嘗試了所有的步驟,但它說「沒有這樣的頁面」。 – bemyhero

+0

add'load_page.php'' var_dump($ _ POST ['page'])'看看裏面的內容是否正確,並確保你有'pages/page_DUMPED_VALUE.html'文件 – Armen