我想創建一個像這裏導航:http://html5.gingerhost.com/jQuery的導航與history.PushState()
我下面這個教程:http://moz.com/blog/create-crawlable-link-friendly-ajax-websites-using-pushstate
實際完成,似乎就像是工作,但我對有疑問如何提高它(我認爲我做錯了什麼,而不是教程的作者)
我的文件夾結構:
localhost
-/try
-script.js
-index.php
-content.php
-/New York
-index.php
-content.php
index.php文件(全部都差不多,只是標題標題和文章是不同的)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Home Page</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<header id="header"><h2>Home</h2></header> <!-- end header -->
<div id="content">
<div id="loading"></div>
<nav>
<ul id="menu">
<li><a href="/Try">Home</a></li>
<li><a href="/Try/Seattle">Seattle</a></li>
<li><a href="/Try/New York">New York</a></li>
<li><a href="/Try/London">London</a></li>
</ul>
</nav>
<div id="main">
<article>
<div id="articletext">
<p>This is home page</p>
</div>
</article> <!-- end post 1 -->
</div> <!-- end main -->
</div> <!-- end content -->
<footer id="footer"><p>Copyright © 2011</p></footer> <!-- end footer -->
</body>
</html>
的script.js(其從本教程只是改變$.getJSON("/content.php",... to $.getJSON(url+"/content.php",
// THIS IS WHERE THE MAGIC HAPPENS
$(function() {
$('nav a').click(function(e) {
$("#loading").show();
href = $(this).attr("href");
loadContent(href);
// HISTORY.PUSHSTATE
history.pushState('', 'New URL: '+href, href);
e.preventDefault();
});
// THIS EVENT MAKES SURE THAT THE BACK/FORWARD BUTTONS WORK AS WELL
window.onpopstate = function(event) {
$("#loading").show();
console.log("pathname: "+location.pathname);
loadContent(location.pathname);
};
});
function loadContent(url){
// USES JQUERY TO LOAD THE CONTENT
$.getJSON(url+"/content.php", {cid: url, format: 'json'}, function(json) {
// THIS LOOP PUTS ALL THE CONTENT INTO THE RIGHT PLACES
$.each(json, function(key, value){
$(key).html(value);
});
$("#loading").hide();
});
// THESE TWO LINES JUST MAKE SURE THAT THE NAV BAR REFLECTS THE CURRENT URL
$('li').removeClass('current');
$('a[href="'+url+'"]').parent().addClass('current');
}
而且我content.php所有文件與其他值相同。
{
"h2":"Home",
"title":"Home",
"article #articletext":"This is Home page"
}
1)我想作者沒有content.php
爲每一頁。我怎麼把它放在一個?那可能嗎?我甚至懷疑我的content.php
看起來應該如何。如果我錯了,請糾正它。
2)我想從content.php
加載頁面內容,有時內容會很長,它會包含很多div,所以我需要在文本中縮進,但是我不能創建「進入」。我的意思是一切都必須在一行,否則它不起作用。顯然它不清楚,以後很難編輯;如何解決這個問題? (我覺得第一個問題的答案是我正在尋找的:P)我試圖把"article #articletext":"<?php include('HomeContent.php'); ?>" instead of "article #articletext":"This is Home page"
放在content.php文件中,但它不起作用,content.php中沒有任何東西加載。
調查此論壇,互聯網和我仍然沒有解決,只是發現沒有回答類似的問題...:<
謝謝你的回答,我以爲我的問題會在其他問題中消失。正如我所說我會從教程重新創建導航,在你的解決方案中,我必須添加「?city = param」來鏈接我不想做的事情,而不太明白如何格式化content.php,如何分割它,我的意思是服務器將如何知道我請求的內容.php的哪一部分,請舉例:)? – user3464829
這是基本的web編程知識,你會把這些信息放到數據庫中,然後在你的content.php中根據查詢字符串參數從數據庫中加載正確的內容。 –
@Chris Brickhouse嗨,你有沒有設法解決這個問題? –