توضیح مثال - صفحه HTML(Example Explained - The HTML Page)

وقتی کاربر یک کاراکتر را در قسمت ورودی بالا تایپ می‌کند، تابع "showResult()" اجرا می‌شود. عملکرد با "onkeyup" فعال می شود
رویداد:




<html>

<head>

<script>

function showResult(str)
{

 
if (str.length==0) {

 
  document.getElementById("livesearch").innerHTML="";

    document.getElementById("livesearch").style.border="0px";

 
  return;

  }

 
if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari

 
  xmlhttp=new XMLHttpRequest();

  }
else {  // code for IE6, IE5

 
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

  }

 
xmlhttp.onreadystatechange=function() {

 
  if (this.readyState==4 && this.status==200) {

 
 
  document.getElementById("livesearch").innerHTML=this.responseText;

      document.getElementById("livesearch").style.border="1px solid #A5ACB2";

    }

  }

 
xmlhttp.open("GET","livesearch.php?q="+str,true);

 
xmlhttp.send();

}

</script>

</head>

<body>



<form>

<input type="text" size="30" onkeyup="showResult(this.value)">

<div id="livesearch"></div>

</form>



</body>

</html>


توضیح کد منبع:


اگر فیلد ورودی خالی باشد (str.length==0)، تابع آن را پاک می کند
محتوای مکان‌نمای lifesearch و از تابع خارج می‌شود.


اگر فیلد ورودی خالی نباشد، تابع showResult() موارد زیر را اجرا می کند:



  • یک شی XMLHttpRequest ایجاد کنید

  • عملکردی را ایجاد کنید که وقتی پاسخ سرور آماده شد اجرا شود

  • درخواست را به فایلی در سرور ارسال کنید

  • توجه کنید که یک پارامتر (q) به URL (با محتوای فیلد ورودی) اضافه شده است