這裏題目的描述方式明顯在指的是後台的商品分類與管理的功能,由於截圖的內容並不完全,我們不清楚這兩個功能是在同一個頁面呈現的還有不同的分頁,基於解題時間的考量,我們直接把兩個功能做在同一頁即可。
- 在
./view/backend/th.php
中建立商品分類的版面html碼,我們打算使用ajax來製作新增分類的功能,所以先在按鈕上加入要呼叫的函式點擊事件1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28<h2 class="ct">商品分類</h2>
<div class="ct">
<label for="">新增大分類</label>
<input type="text" name="big" id="big">
<button onclick="addType('big')">新增</button>
</div>
<div class="ct">
<label for="">新增中分類</label>
<select name="bigs" id="bigs"></select>
<input type="text" name="mid" id="mid">
<button onclick="addType('mid')">新增</button>
</div>
<table class="all">
<tr class="tt">
<td><?=$big['name'];?></td>
<td class="ct">
<button>修改</button>
<button>刪除</button>
</td>
</tr>
<tr class="pp ct">
<td></td>
<td>
<button>修改</button>
<button>刪除</button>
</td>
</tr>
</table>
- 撰寫新增大分類和新增中分類的js函式,使用一個參數來控制要新增的項目,完成後重新載入頁面即可
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15function addType(type){
let data
switch(type){
case "big":
data={name:$(`#${type}`).val(),big:0}
break;
case "mid":
data={name:$(`#${type}`).val(),big:$("#bigs").val()}
break;
}
$.post("./api/save_type.php",data,()=>{
location.reload();
})
} - 在
/api/save_type.php
中撰寫儲存分類資料的方法1
2
3//api/save_type.php 中只需要把ajax以POST傳來的資料存進資料表即可
include_once "../base.php";
$Type->save($_POST); - 在
./view/backend/th.php
中接著撰寫使用ajax的方式來載入的大分類選單,考量到後面新增/編輯商品時也會再次使用到載入選單的功能,因此在api的設計上,儘可能讓通用性可以高一點,減少撰寫重覆程式碼的狀況。1
2
3
4
5
6getBigs()
function getBigs(){
$.get("./api/bigs.php",(bigs)=>{
$("#bigs").html(bigs)
})
} - 在
/api/big.php
中撰寫撈出大分類選項程式碼1
2
3
4
5include_once "../base.php";
$rows=$Type->all(['big'=>0]);
foreach($rows as $row){
echo "<option value='{$row['id']}'>{$row['name']}</option>";
}
接著我們開始來撰寫把分類顯示在畫面上的程式碼,這邊要小心巢狀式語法,避免搞錯順序。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30<table class="all">
<?php
$bigs=$Type->all(['big'=>0]);
foreach($bigs as $big){
<tr class="tt">
<td><?=$big['name'];?></td>
<td class="ct">
<button onclick="edit(this,<?=$big['id'];?>)">修改</button>
<button onclick="del('Type',<?=$big['id'];?>)">刪除</button>
</td>
</tr>
<?php
if($Type->hasMid($big['id'])>0){
$mids=$Type->getMids($big['id']);
foreach($mids as $mid){
<tr class="pp ct">
<td><?=$mid['name'];?></td>
<td>
<button onclick="edit(this,<?=$mid['id'];?>)">修改</button>
<button onclick="del('Type',<?=$mid['id'];?>)">刪除</button>
</td>
</tr>
<?php
}
}
}
?>
</table>最後撰寫編輯分類的功能,這邊我們使用js內建的prompt()來提供編輯的彈出畫面,然後再以ajax的方式將修改後的文字送到
./api/save_type.php
去做資料表的更新,然後再利用DOM tree
的方式直接在畫面上更新文字,或是省事點的直接用location.reload()
來重新載入頁面也可以。1
2
3
4
5
6
7
8
9
10function edit(dom,id){
let text=$(dom).parent().prev().text()
let name=prompt("請輸入你要修改的類別名稱",text);
if(name!=null){
$.post("./api/save_type.php",{name,id},()=>{
//location.reload();
$(dom).parent().prev().text(name)
})
}
}
- 在這邊要注意一下,題目中有暗示版面不能因為內容而自動擴展高度,所以我們們要在css中把
#right
改成固定高度,並且加上overflow:auto
,讓版面會自動出現滾軸。1
2
3
4
5
6
7
8
9#right
{
display:inline-block;
width:65%;
padding:2%;
height:550px;
border:#000 1px solid;
overflow:auto;
}