PHP - AJAX 与 PHP

ゞ 浴缸里的玫瑰 2024-04-07 11:15 150阅读 0赞

AJAX 被用于创建交互性更强的应用程序。


AJAX PHP 实例

下面的实例将演示当用户在输入框中键入字符时,网页如何与 Web 服务器进行通信:

实例

尝试在输入框中输入一个名字,如:Anna:

姓名:

返回值:


实例解释 - HTML 页面

当用户在上面的输入框中键入字符时,会执行 “showHint()” 函数。该函数由 “onkeyup” 事件触发:

  1. <html>
  2. <head>
  3. <script>
  4. function showHint(str)
  5. {
  6. if (str.length==0)
  7. {
  8. document.getElementById("txtHint").innerHTML="";
  9. return;
  10. }
  11. if (window.XMLHttpRequest)
  12. {
  13. // IE7+, Firefox, Chrome, Opera, Safari 浏览器执行的代码
  14. xmlhttp=new XMLHttpRequest();
  15. }
  16. else
  17. {
  18. //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","gethint.php?q="+str,true);
  29. xmlhttp.send();
  30. }
  31. </script>
  32. </head>
  33. <body>
  34. <p><b>在输入框中输入一个姓名:</b></p>
  35. <form>
  36. 姓名: <input type="text" onkeyup="showHint(this.value)">
  37. </form>
  38. <p>返回值: <span id="txtHint"></span></p>
  39. </body>
  40. </html>

源代码解释:

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

如果输入框不是空的,那么 showHint() 会执行以下步骤:

  • 创建 XMLHttpRequest 对象
  • 创建在服务器响应就绪时执行的函数
  • 向服务器上的文件发送请求
  • 请注意添加到 URL 末端的参数(q)(包含输入框的内容)

PHP 文件

上面这段通过 JavaScript 调用的服务器页面是名为 “gethint.php” 的 PHP 文件。

“gethint.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. //从请求URL地址中获取 q 参数
  34. $q=$_GET["q"];
  35. //查找是否由匹配值, 如果 q>0
  36. if (strlen($q) > 0)
  37. {
  38. $hint="";
  39. for($i=0; $i<count($a); $i++)
  40. {
  41. if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
  42. {
  43. if ($hint=="")
  44. {
  45. $hint=$a[$i];
  46. }
  47. else
  48. {
  49. $hint=$hint." , ".$a[$i];
  50. }
  51. }
  52. }
  53. }
  54. // 如果没有匹配值设置输出为 "no suggestion"
  55. if ($hint == "")
  56. {
  57. $response="no suggestion";
  58. }
  59. else
  60. {
  61. $response=$hint;
  62. }
  63. //输出返回值
  64. echo $response;
  65. ?>

解释:如果 JavaScript 发送了任何文本(即 strlen($q) > 0),则会发生:

  1. 查找匹配 JavaScript 发送的字符的姓名
  2. 如果未找到匹配,则将响应字符串设置为 “no suggestion”
  3. 如果找到一个或多个匹配姓名,则用所有姓名设置响应字符串
  4. 把响应发送到 “txtHint” 占位符

发表评论

表情:
评论列表 (有 0 条评论,150人围观)

还没有评论,来说两句吧...

相关阅读