中央論壇 - CENTER BBS

標題: [PHP] AJAX & MySQL教學範例 - AJAX基本使用 PHP應用 [打印本頁]

作者: 死神    時間: 2013-10-16 11:57
標題: [PHP] AJAX & MySQL教學範例 - AJAX基本使用 PHP應用
本篇介紹AJAX應用在PHP&MYSQL的實例,實作可以在W3School操作,本篇因不做跨網域所以僅介紹程式碼。

HTML程式碼:
  1. <html>
  2. <head>
  3. <script>
  4. function showUser(str)
  5. {
  6. if (str=="")
  7.   {
  8.   document.getElementById("txtHint").innerHTML="";
  9.   return;
  10.   }
  11. if (window.XMLHttpRequest)
  12.   {// code for IE7+, Firefox, Chrome, Opera, Safari
  13.   xmlhttp=new XMLHttpRequest();
  14.   }
  15. else
  16.   {// code for IE6, IE5
  17.   xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  18.   }
  19. xmlhttp.onreadystatechange=function()
  20.   {
  21.   if (xmlhttp.readyState==4 && xmlhttp.status==200)
  22.     {
  23.     document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
  24.     }
  25.   }
  26. xmlhttp.open("GET","getuser.php?q="+str,true);
  27. xmlhttp.send();
  28. }
  29. </script>
  30. </head>
  31. <body>

  32. <form>
  33. <select name="users" onchange="showUser(this.value)">
  34. <option value="">Select a person:</option>
  35. <option value="1">Peter Griffin</option>
  36. <option value="2">Lois Griffin</option>
  37. <option value="3">Glenn Quagmire</option>
  38. <option value="4">Joseph Swanson</option>
  39. </select>
  40. </form>
  41. <br>
  42. <div id="txtHint"><b>Person info will be listed here.</b></div>

  43. </body>
  44. </html>
複製代碼
PHP程式碼:
  1. <?php
  2. $q = intval($_GET['q']);

  3. $con = mysqli_connect('localhost','peter','abc123','my_db');
  4. if (!$con)
  5.   {
  6.   die('Could not connect: ' . mysqli_error($con));
  7.   }

  8. mysqli_select_db($con,"ajax_demo");
  9. $sql="SELECT * FROM user WHERE id = '".$q."'";

  10. $result = mysqli_query($con,$sql);

  11. echo "<table border='1'>
  12. <tr>
  13. <th>Firstname</th>
  14. <th>Lastname</th>
  15. <th>Age</th>
  16. <th>Hometown</th>
  17. <th>Job</th>
  18. </tr>";

  19. while($row = mysqli_fetch_array($result))
  20.   {
  21.   echo "<tr>";
  22.   echo "<td>" . $row['FirstName'] . "</td>";
  23.   echo "<td>" . $row['LastName'] . "</td>";
  24.   echo "<td>" . $row['Age'] . "</td>";
  25.   echo "<td>" . $row['Hometown'] . "</td>";
  26.   echo "<td>" . $row['Job'] . "</td>";
  27.   echo "</tr>";
  28.   }
  29. echo "</table>";

  30. mysqli_close($con);
  31. ?>
複製代碼
參考:W3SCHOOL




歡迎光臨 中央論壇 - CENTER BBS (https://www.centerbbs.com/) Powered by Discuz! X3