問題描述
AJAX/PHP/JS ‑ 無法將頁面內容加載到容器中 (AJAX/PHP/JS ‑ Cannot load page content into container)
我不斷收到“沒有這樣的頁面!” 在我嘗試使用按鈕更改內容時隨時發送消息。 這是 index.html:
<!DOCTYPE html PUBLIC "‑//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1‑transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http‑equiv="Content‑Type" content="text/html; charset=utf‑8" />
<title>eWorld</title>
<link rel="stylesheet" type="text/css" href="/css/style.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="js/script.js"></script>
</head>
<body>
<div id="rounded">
<div id="main" class="container">
<h1>eWORLD</h1>
<h2>You make difference.</h2>
<ul id="navigation">
<li><a href="#forum">Forum</a></li>
<li><a href="#about">About</a></li>
<li><a href="#register">Register</a></li>
<li><a href="#login" target=pageContent>Login</a></li>
<li><img id="loading" src="img/ajax_load.gif" alt="loading" /></li>
</ul>
</div>
<div class="clear"></div>
</div>
<div class="clear"></div>
<div id="pageContent">
</div>
<div class="clear"></div></div>
<div align="center" class="#footer">eWorld</div>
</body>
</html>
script.js:
var default_content="";
$(document).ready(function(){
checkURL();
$('ul li a').click(function (e){
checkURL(this.hash);
});
default_content = $('#pageContent').html();
setInterval("checkURL()",250);
});
var lasturl="";
function checkURL(hash)
{
if(!hash) hash=window.location.hash;
if(hash != lasturl)
{
lasturl=hash;
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 = $_POST['page'];
$newstr = str_replace("#","", $page);
if (!file_exists('pages/'.$newstr.'.html'))
echo file_get_contents('pages/'.$newstr.'.html');
else echo 'There is no such page!';
?>
腳本似乎工作正常,但不知何故無法進入新頁面的目錄(即 /pages/forum.html ; /pages/login.html 等)。如果有人能告訴我我在哪裡犯了錯誤,將不勝感激...... :)
參考解法
方法 1:
You are trying to get .hash of DOM element:
$('ul li a').click(function (e){
checkURL(this.hash);
Instead get the href attribute:
checkURL(this.attr("href"));
.hash only works on URL object
Also, this first use of checkURL(); after documentReady should be throwing errors as it does not match the method definition
方法 2:
The solving was as both Auris and Pointy explained. First of all, getting the href atribute made resolved errors in console with processing. Also !file_exists meant, as Pointy said, "if the file does not exist". Everything working perfectly right now, thanks for support!
(by Damian Doman、Auris、Damian Doman)