0%

[技能檢定]題組二 步驟7 建置會員註冊功能

由於題目有先附帳號資料,所以我們可以先把資料表建好,並直接在資料表中建立資料,進而先完成會員登入的功能;接著我們要來製作註冊會員的功能。

建立註冊畫面

front/reg.php 畫面html碼

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
<fieldset>
<legend>會員註冊</legend>
<div style="color:red">*請設定您要註冊的帳號及密碼(最長12個字元)</div>
<table>
<tr>
<td>Step1:登入帳號</td>
<td><input type="text" name="acc" id="acc"></td>
</tr>
<tr>
<td>Step2:登入密碼</td>
<td><input type="password" name="pw" id="pw"></td>
</tr>
<tr>
<td>Step3:再次確認密碼</td>
<td><input type="password" name="pw2" id="pw2"></td>
</tr>
<tr>
<td>Step4:信箱(忘記密碼時使用)</td>
<td><input type="text" name="email" id="email"></td>
</tr>
<tr>
<td>
<button onclick="reg()">註冊</button>
<button onclick="reset()">清除</button>
</td>
<td></td>
</tr>
</table>
</fieldset>

撰寫前端表單資料處理的javascript程式

清空資料函式

由於清空表單的功能在很多地方用得到,因此可以把這個函式搬到外連的 /js/js.js 中,這樣隨著頁面的引入js檔案,在任何地方都可以隨時呼叫 clean() 來使用

1
2
3
4
function clean(){
//針對特定類型的input標籤進行資料清空的動作
$("input[type='text'],input[type='password'],input[type='number'],input[type='radio']").val("");
}

表單資料檢查及送出函式

由於題目提到要檢查帳號是否已被使用了,因此這邊使用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
29
30
31
32
33
34
function reg(){

//宣告一個物件用來存放表單目前被填入的資料
let info={
acc:$("#acc").val(),
pw:$("#pw").val(),
pw2:$("#pw2").val(),
email:$("#email").val(),
}

//先檢查有沒有任何一個欄位是空白的
if(info.acc=='' || info.pw=='' || info.pw2=='' || info.email==''){
alert("不可空白");
}else if(info.pw!=info.pw2){ //接著檢查兩個密碼欄位內容是否一致
alert("密碼錯誤");
}else{

//先將帳號送去chk_acc.php進行檢查
$.post("./api/chk_acc.php",{acc:info.acc},(res)=>{

//如果回傳的結果不是0,表示這個帳號在資料表中已經存在了
if(parseInt(res)!==0){
alert("帳號重複");
}else{

//如果回傳的結果是0,表示資料表中沒有這個帳號,
//此時就可以把表單資料送到後端的reg.php中進行新
$.post("./api/reg.php",info,()=>{
alert("註冊完成,歡迎加入")
})
}
})
}
}