依據題目描述,分類網誌不使用資料表也是可以的,但是因為我想節省一直開檔複製貼上的工作,所以我的做法是先把文章都匯入到資料庫,這樣後台的文章管理和前台的分類網誌、最新文章、人氣文章的功能都用得到
。

建立分類網誌畫面
/view/front/po.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| <div> 目前位置:首頁 > 分類網誌 > <span id='header'>健康新知</span> </div> <div style="display:flex"> <fieldset style="width:150px;"> <legend>分類網誌</legend> <div><a class='cat' data-type='1' href="#">健康新知</a></div> <div><a class='cat' data-type='2' href="#">菸害防治</a></div> <div><a class='cat' data-type='3' href="#">癌症防治</a></div> <div><a class='cat' data-type='4' href="#">慢性病防治</a></div> </fieldset> <fieldset style="width:550px;"> <legend>文章列表</legend> <div id="lists"></div>
<div id="post"></div> </fieldset> </div>
|
建立分類項目點擊置換上方導引文字功能
/view/front/po.php部份
1 2 3 4 5 6
| $(".cat").on("click",function(){
$("#header").text($(this).text()) })
|
建立取得分類項目文章標題列表功能
這裏我們使用ajax來取得分類項目的文章標題
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| getList(1);
$(".cat").on("click",function(){
$("#header").text($(this).text());
let type=$(this).data('type') getList(type) })
function getList(type){ $.get("./api/get_list.php",{type},(list)=>{ $("#post").html("") $("#lists").html(list) }) }
|

建立取得單一文章函式
1 2 3 4 5 6 7
| function getPost(id){ $.get("./api/get_post.php",{id},(post)=>{ $("#lists").html(""); $("#post").html(post) }) }
|
撰寫後端回傳文章標題列表程式
/api/get_list.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| include_once "../base.php";
$posts=$News->all(['type'=>$_GET['type']]);
foreach($posts as $post){ echo "<div>"; echo "<a href='Javascript:getPost({$post['id']})'>"; echo $post['title']; echo "</a>"; echo "</div>"; }
|
撰寫後端回傳文章程式
/api/get_post.php
1 2 3 4 5 6 7 8 9 10 11
| include_once "../base.php";
$post=$News->find($_GET['id']);
echo "<span style='font-weight:bolder'>".$post['title']."</span>"; echo "<br>";
echo nl2br($post['text']);
|
