编写PHP文件json.php
<?
$arr=array('Alpha','Bravo','Charlie','Celta','Echo','Foxtrot','Golf','Hotel','India','Juliett','Kilo','Lima','Mike','November','Oscar','Papa','Quebec','Romeo','Sierra','Tango','Uniform','Victor','Whiskey','X-ray','Yankee','Zulu');
$search=strtolower($_POST['search']);
$hits=array();
if(!empty($search)){
 foreach($arr as $name){
  if(strpos(strtolower($name),$search)===0)
  {
   $hits[]=$name;
  }
 }
}
echo json_encode($hits);
 
编写HTML文件json.html
<html>
 <head>
  <script src="json.js"n type="text/javascript"></script>
  <script type="text/javascript">
   var xhr;
   function getXHR(){
    var req;
    if(window.XMLHttpRequest){
     req=new XMLHttpRequest();
     
    }else if(window.ActiveXObject){
     req=new ActiveXObject("Microsoft.XMLHTTP");
    }
    return req;
   }
   function suggest(){
    if(xhr && xhr.readyState!=0)
    {
     xhr.abort();
    }
    xhr=getXHR();
    
    url="http://www.ydd.cn/demo/suggest.php";
    xhr.open("POST",url,true);
    
    searchValue=document.getElementById("search").value;
    //alert(searchValue);
    data="search="+encodeURIComponent(searchValue);
    xhr.onreadystatechange=readyStateChange;
    xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    
    
    xhr.send(data);
   }
   function readyStateChange(){
    if(xhr.readyState==4){
   
     if(xhr.responseText && xhr.status==200){
     alert(xhr.responseText);
      json=xhr.responseText;
      
      try{
       suggestionArr=json.parseJSON();
      }catch(e){
      
      }
      alert(suggestionArr);
      tmpHtml="";
      for(i=0,len=suggestionArr.length;i<len;i++)
      {
       tmpHtml+=suggestionArr[i]+"<br />";
      }
      div=document.getElementById("suggestions");
      div.innerHTML=tmpHtml;
     }
    
    }
   }
  </script>
 </head>
 <body>
  <input id="search" type="text" onKeyUp="suggest()"/>
  <div id="suggestions"></div>
 </body>
</html>