في هذا الدرس 3تصفّح المواضيع
يوضح المثال التالي كيف يمكن لصفحة الويب الاتصال بخادم الويب بينما يكتب المستخدم الأحرف في حقل الإدخال:
في المثال السابق عندما يقوم المستخدم بكتابة احرف في حقل الادخال سوف يتم تنفيذ الدالة ( )showHint وذلك باستخدام ال event التالي "onkeyup"
Example
HTML
<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", "/files/gethint.php?q=" + str);
xmlhttp.send();
}
}
</script>
شرح الكود السابق
اولا قمنا بالتحقق من اذا كان حقل الادخال فارغا او لا باستخدام ( str.length==0 )
- فأذا كان فارغا يتم الخروج من تنفيذ الدالة
- واذا لم يكن فارغا تنفيذ ما يلي
- يتم انشاء العنصر "XMLHttpRequest"
- يتم انشاء الدالة عندما تكون استجابة الخادم جاهزة
- يتم ارسال طلب الي الخادم لأحضار ملف "gethint.php"
- يحمل المتغير "str" القيمة التي قام بأدخالها المستخدم في حقل الادخال
يتحقق ملف PHP من مجموعة من الأسماء وبعد ذلك يقوم بأعادة الاسماء المتشابهة الي المتصفح
HTML
<?php
/* Array with names */
$a[] = "Ahmed";
$a[] = "Ali";
$a[] = "Adel";
$a[] = "Mohamed";
$a[] = "Maged";
$a[] = "Mahmoud";
$a[] = "Marawan";
$a[] = "Moustaf";
$a[] = "Nader";
$a[] = "Noah";
$a[] = "Nasir";
$a[] = "Nour";
$a[] = "Nadia";
$a[] = "badr";
$a[] = "Bilal";
$a[] = "Youssef";
$a[] = "Younes";
$a[] = "Hussein";
$a[] = "Hoda";
$a[] = "Hamza";
$a[] = "Hadeel";
$a[] = "Seham";
$a[] = "saleh";
$a[] = "salah";
$a[] = "samar";
$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;
?>
رحلتك في الدرس
—سجّل الدخول لحفظ تقدمك
تابع إنجاز المواضيع والمصطلحات والمهام، وكمّل من آخر خطوة على أي جهاز.