因為最後一堂課同學們一心都撲在了期末作業上
所以我為同學們準備了比較輕鬆的內容
利用Ajax更新部分頁面區塊,以節省資源

利用Ajax處理事件,比如刪除資料不需要refresh整個page
本周是與ajax相關的基本知識:

先測試

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!DOCTYPE html>
<html leng="utf-8">
<head>
<title>Ajax 練習</title>
</head>
<body>
<button id="btn">test</button>
<script>
document.getElementById('btn').addEventListener('click',myfun);
function myfun(){
document.write("success!");
}
</script>
</body>
</html>

成果應該如下:

Web API - XMLHttpRequest

藉由 XMLHttpRequest(XHR)物件的方式來存取伺服器端的資料,可以讓你直接經由指定的 URL 擷取資料卻不用刷新整個網頁。
相關的詳細說明:https://developer.mozilla.org/zh-TW/docs/Web/API/XMLHttpRequest

實作部分,在function裡面多加兩行

1
2
var xhr=new XMLHttpRequest();
console.log(xhr);

在瀏覽器裡按F12或直接右鍵檢查

200: OK
403: Forbbiden
404: Not Found

使用XMLHttpRequest打開文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function myfun(){
var xhr=new XMLHttpRequest();
xhr.open('GET','test.txt',true);
console.log(xhr);
xhr.onload=function(){
if(xhr.status==200){
document.write(this.responseURL+"<br>"+this.responseText);
}else{
document.write("File not found");
}
}

xhr.send();
}

服務器響應 Server Response

onreadystatechange屬性

  • readystate:保留XMLHttpRequest的狀態
    • 0: request not initialized
    • 1: server connection established
    • 2: request received
    • 3: processing request
    • 4: request finished and response is ready
  • onreadystatechange:定義當readyState更改時要執行的函數
  • status:常見的error代號如404
  • statusText:error代號的說明

選擇選單、顯示相關資料

index.php

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
35
36
37
38
39
40
41
<!DOCTYPE html>
<html leng="utf-8">
<head>
<title>Ajax 練習</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
<script>
function showUser(str){
if(str==''){
document.getElementById("txtHint").innerHTML="no user selected";
return;
}else{
var xhr=new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
}
console.log(xhr);
}

xhr.open("GET","user.php?name="+str,true);
xhr.send();
}
</script>
</head>
<body>

<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person</option>
<option value="1">haha</option>
<option value="2">teacher</option>
</select>
</form>
<br>
<div id="txtHint"><b>Detail about user will show here...</b></div>

</body>
</html>

user.php

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
<?php
$name=$_GET['name'];
$conn = mysqli_connect('localhost','root','','db_test');
if (!$conn) {
die('Could not connect: ' . mysqli_error($con));
}
$sql="SELECT * FROM ajax WHERE id='".$name."'";
$result = mysqli_query($conn, $sql);
echo "<table class='table'>
<tr>
<th>id</th>
<th>name</th>
<th>email</th>
<th>password</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "<td>" . $row['password'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($conn);
?>