ล่าสุดการพัฒนาเว็บบทเรียน
 

AJAXตัวอย่าง PHP


AJAX ถูกนำมาใช้ในการสร้างโปรแกรมการโต้ตอบมากขึ้น


AJAX PHP ตัวอย่าง

ตัวอย่างต่อไปนี้จะแสดงให้เห็นว่าหน้าเว็บที่สามารถสื่อสารกับเว็บเซิร์ฟเวอร์ในขณะที่ตัวละครประเภทของผู้ใช้ในช่องใส่:

ตัวอย่าง

Start typing a name in the input field below:

First name:

Suggestions:



ตัวอย่างอธิบาย

ในตัวอย่างข้างต้นเมื่อผู้ใช้พิมพ์ตัวละครในช่องใส่ฟังก์ชั่นที่เรียกว่า "showHint()" จะถูกดำเนินการ

ฟังก์ชั่นจะถูกเรียกโดย onkeyup เหตุการณ์

นี่คือรหัส HTML:

ตัวอย่าง

<html>
<head>
<script>
function showHint(str) {
    if (str.length == 0) {
        document.getElementById("txtHint").innerHTML = "";
        return;
    } else {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
            }
        };
        xmlhttp.open("GET", "gethint.php?q=" + str, true);
        xmlhttp.send();
    }
}
</script>
</head>
<body>

<p><b>Start typing a name in the input field below:</b></p>
<form>
First name: <input type="text" onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>
ลองตัวเอง»

คำอธิบายรหัสสินค้า:

ขั้นแรกให้ตรวจสอบว่าช่องใส่เป็นที่ว่างเปล่า (str.length == 0) หากเป็นเช่นนั้นล้างเนื้อหาของ txtHint ตัวยึดและออกจากฟังก์ชั่น

แต่ถ้าช่องใส่ไม่ว่างทำต่อไปนี้:

  • สร้าง XMLHttpRequest วัตถุ
  • สร้างฟังก์ชั่นที่จะดำเนินการเมื่อตอบกลับของเซิร์ฟเวอร์ที่มีความพร้อม
  • ส่งคำขอร้องออกไปไฟล์ PHP (gethint.php) บนเซิร์ฟเวอร์
  • ขอให้สังเกตว่า q พารามิเตอร์จะถูกเพิ่ม gethint.php?q="+str
  • str ตัวแปรถือเนื้อหาของข้อมูลการป้อนข้อมูล

PHP ได้ไฟล์ - "gethint.php"

ไฟล์ PHP ตรวจสอบอาร์เรย์ของชื่อและผลตอบแทนที่สอดคล้องกัน name(s) เบราว์เซอร์:

<?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;
?>