AJAX非同步實現

來源:互聯網
上載者:User

標籤:body   key   action   send   ==   utf-8   url   網頁   php   

AJAX 最大的優點是在不重新載入整個頁面的情況下,可以與伺服器交換資料並更新部分網頁內容。

<head><meta charset="utf-8"><script>function showHint(str){  var xmlhttp;  if (str.length==0)  {     document.getElementById("txtHint").innerHTML="";    return;  }  if (window.XMLHttpRequest)  {    // IE7+, Firefox, Chrome, Opera, Safari 瀏覽器執行代碼    xmlhttp=new XMLHttpRequest();  }  else  {    // IE6, IE5 瀏覽器執行代碼    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");  }  xmlhttp.onreadystatechange=function()  {    if (xmlhttp.readyState==4 && xmlhttp.status==200)    {      document.getElementById("txtHint").innerHTML=xmlhttp.responseText;    }  }  xmlhttp.open("GET","/try/ajax/gethint.php?q="+str,true);  xmlhttp.send();}</script></head><body><h3>在輸入框中嘗試輸入字母 a:</h3><form action=""> 輸入姓名: <input type="text" id="txt1" onkeyup="showHint(this.value)" /></form><p>提示資訊: <span id="txtHint"></span></p> 

如果輸入框不為空白,showHint() 函數執行以下任務:

  • 建立 XMLHttpRequest 對象
  • 當伺服器響應就緒時執行函數
  • 把請求發送到伺服器上的檔案
  • 請注意我們向 URL 添加了一個參數 q (帶有輸入框的內容)

   gethint.php:

<?php// Fill up 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[]="Tove";$a[]="Unni";$a[]="Violet";$a[]="Liza";$a[]="Elizabeth";$a[]="Ellen";$a[]="Wenche";$a[]="Vicky";//get the q parameter from URL$q=$_GET["q"];if (strlen($q) > 0){  $hint="";  for($i=0; $i<count($a); $i++)  {    if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))    {      if ($hint=="")      {        $hint=$a[$i];      }      else      {        $hint=$hint." , ".$a[$i];      }    }  }}if ($hint == ""){  $response="no suggestion";}else{  $response=$hint;}//output the responseecho $response;?>

 

AJAX非同步實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.