ตัวอย่าง AJAX PHP
AJAX ใช้เพื่อสร้างแอปพลิเคชันแบบโต้ตอบมากขึ้น
ตัวอย่าง AJAX PHP
ตัวอย่างต่อไปนี้แสดงให้เห็นว่าหน้าเว็บสามารถสื่อสารกับเว็บเซิร์ฟเวอร์ได้อย่างไรในขณะที่ผู้ใช้พิมพ์อักขระในช่องใส่ข้อมูล:
ตัวอย่าง
Start typing a name in the input field below:
Suggestions:
First name:
ตัวอย่างที่อธิบาย
ในตัวอย่างข้างต้น เมื่อผู้ใช้พิมพ์อักขระในช่องป้อนข้อมูล ฟังก์ชันที่เรียกว่าshowHint()
จะถูกดำเนินการ
ฟังก์ชันถูกทริกเกอร์โดยonkeyup
เหตุการณ์
นี่คือรหัส:
ตัวอย่าง
<p>Start typing a name in the input field below:</p>
<p>Suggestions: <span id="txtHint"></span></p>
<form>
First name: <input type="text" onkeyup="showHint(this.value)">
</form>
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
document.getElementById("txtHint").innerHTML = this.responseText;
}
xmlhttp.open("GET", "gethint.php?q=" + str);
xmlhttp.send();
}
}
</script>
คำอธิบายรหัส:
ขั้นแรก ให้ตรวจสอบว่าช่องป้อนข้อมูลว่างเปล่าหรือไม่ (str.length == 0) หากใช่ ให้ล้างเนื้อหาของตัวยึดตำแหน่ง txtHint และออกจากฟังก์ชัน
อย่างไรก็ตาม หากช่องป้อนข้อมูลไม่ว่างเปล่า ให้ทำดังต่อไปนี้:
- สร้างวัตถุ XMLHttpRequest
- สร้างฟังก์ชันที่จะดำเนินการเมื่อการตอบสนองของเซิร์ฟเวอร์พร้อม
- ส่งคำขอไปที่ไฟล์ PHP (gethint.php) บนเซิร์ฟเวอร์
- สังเกตว่ามีการเพิ่มพารามิเตอร์ q gethint.php?q="+str
- ตัวแปร str เก็บเนื้อหาของช่องใส่
ไฟล์ PHP - "getin.php"
ไฟล์ PHP ตรวจสอบอาร์เรย์ของชื่อ และส่งคืนชื่อที่ตรงกันไปยังเบราว์เซอร์:
<?php
// Array with names
$a[] = "Anna";
$a[] = "Brittany";
$a[] = "Cinderella";
$a[] = "Diana";
$a[] = "Eva";
$a[] = "Fiona";
$a[] = "Gunda";
$a[] = "Hege";
$a[] = "Inga";
$a[] = "Johanna";
$a[] = "Kitty";
$a[] = "Linda";
$a[] = "Nina";
$a[] = "Ophelia";
$a[] = "Petunia";
$a[] = "Amanda";
$a[] = "Raquel";
$a[] = "Cindy";
$a[] = "Doris";
$a[] = "Eve";
$a[] = "Evita";
$a[] = "Sunniva";
$a[] = "Tove";
$a[] = "Unni";
$a[] = "Violet";
$a[] = "Liza";
$a[] = "Elizabeth";
$a[] = "Ellen";
$a[] = "Wenche";
$a[] = "Vicky";
// get the q parameter from URL
$q = $_REQUEST["q"];
$hint = "";
// lookup all hints from array if $q is different from ""
if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint = $name;
} else {
$hint .= ", $name";
}
}
}
}
// Output "no suggestion" if no hint was found or output correct values
echo $hint === "" ? "no suggestion" : $hint;
?>