个人博客  CSDN 久艾分享  

程序爱好者QQ群:程序爱好者

初识Ajax---简单的Ajax应用实例

原文: http://www.ido321.com/347.html

从网页前端输入提示范围内的字符,然后显示从后台返回的结果

   1: <html>
   2: <head>
   3: <meta http-equiv="content-type" content="text/html;charset=utf-8">
   4: <script type="text/javascript">
   5: function showHint(str)
   6: {
   7: var xmlhttp;
   8: if (str.length==0)
   9:   { 
  10:   document.getElementById("txtHint").innerHTML="";
  11:   return;
  12:   }
  13: if (window.XMLHttpRequest)
  14:   {// code for IE7+, Firefox, Chrome, Opera, Safari
  15:   xmlhttp=new XMLHttpRequest();
  16:   }
  17: else
  18:   {// code for IE6, IE5
  19:   xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  20:   }
  21: xmlhttp.onreadystatechange=function()
  22:   {
  23:   if (xmlhttp.readyState==4 && xmlhttp.status==200)
  24:     {
  25:     document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
  26:     }
  27:   }
  28: xmlhttp.open("GET","ajax.php?q="+str,true);
  29: xmlhttp.send();
  30: }
  31: </script>
  32: </head>
  33: <body>
  34:  
  35: <h3>请在下面的输入框中键入字母(A - Z):</h3>
  36: <form action=""> 
  37: 姓氏:<input type="text" id="txt1" onkeyup="showHint(this.value)" />
  38: </form>
  39: <p>建议:<span id="txtHint"></span></p> 
  40:  
  41: </body>
  42: </html>

如果输入框为空 (str.length==0),则该函数清空 txtHint 占位符的内容,并退出函数。

如果输入框不为空,showHint() 函数执行以下任务:

  • 创建 XMLHttpRequest 对象
  • 当服务器响应就绪时执行函数
  • 把请求发送到服务器上的文件
  • 请注意我们向 URL 添加了一个参数 q (带有输入框的内容)

php:

   1: <?php
   2: // 用名字来填充数组
   3: $a[]="Anna";
   4: $a[]="Brittany";
   5: $a[]="Cinderella";
   6: $a[]="Diana";
   7: $a[]="Eva";
   8: $a[]="Fiona";
   9: $a[]="Gunda";
  10: $a[]="Hege";
  11: $a[]="Inga";
  12: $a[]="Johanna";
  13: $a[]="Kitty";
  14: $a[]="Linda";
  15: $a[]="Nina";
  16: $a[]="Ophelia";
  17: $a[]="Petunia";
  18: $a[]="Amanda";
  19: $a[]="Raquel";
  20: $a[]="Cindy";
  21: $a[]="Doris";
  22: $a[]="Eve";
  23: $a[]="Evita";
  24: $a[]="Sunniva";
  25: $a[]="Tove";
  26: $a[]="Unni";
  27: $a[]="Violet";
  28: $a[]="Liza";
  29: $a[]="Elizabeth";
  30: $a[]="Ellen";
  31: $a[]="Wenche";
  32: $a[]="Vicky";
  33:  
  34: //获得来自 URL 的 q 参数
  35: $q=$_GET["q"];
  36:  
  37: //如果 q 大于 0,则查找数组中的所有提示
  38: if (strlen($q) > 0)
  39:   {
  40:   $hint="";
  41:   for($i=0; $i<count($a); $i++)
  42:     {
  43:     if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
  44:       {
  45:       if ($hint=="")
  46:         {
  47:         $hint=$a[$i];
  48:         }
  49:       else
  50:         {
  51:         $hint=$hint." , ".$a[$i];
  52:         }
  53:       }
  54:     }
  55:   }
  56:  
  57: // 如果未找到提示,则把输出设置为 "no suggestion"
  58: // 否则设置为正确的值
  59: if ($hint == "")
  60:   {
  61:   $response="no suggestion";
  62:   }
  63: else
  64:   {
  65:   $response=$hint;
  66:   }
  67:  
  68: //输出响应
  69: echo $response;
  70: ?>

效果

打包下载

posted @ 2014-08-24 11:00  淡忘~浅思  阅读(189)  评论(0编辑  收藏  举报