一、数据库数据
mysql> select * from websites; +----+--------------+---------------------------+-------+---------+ | id | name | url | alexa | country | +----+--------------+---------------------------+-------+---------+ | 1 | Google | https://www.google.cm/ | 1 | USA | | 2 | 淘宝 | https://www.taobao.com/ | 13 | CN | | 3 | 菜鸟教程 | http://www.runoob.com/ | 4689 | CN | | 4 | 微博 | http://weibo.com/ | 20 | CN | | 5 | Facebook | https://www.facebook.com/ | 3 | USA | +----+--------------+---------------------------+-------+---------+ 5 rows in set (0.01 sec)
二、前端页面实现
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>菜鸟教程(runoob.com)</title> <script> function showSite(str) { if (str=="") { 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","getsite_mysql.php?q="+str,true); xmlhttp.send(); } </script> </head> <body> <form> <select name="users" onchange="showSite(this.value)"> <option value="">选择一个网站:</option> <option value="1">Google</option> <option value="2">淘宝</option> <option value="3">菜鸟教程</option> <option value="4">微博</option> <option value="5">Facebook</option> </select> </form> <br> <div id="txtHint"><b>网站信息显示在这里……</b></div> </body> </html>
三、后端代码
<?php $q = isset($_GET["q"]) ? intval($_GET["q"]) : ''; if(empty($q)) { echo '请选择一个网站'; exit; } $con = mysqli_connect('localhost','root','123456'); if (!$con) { die('Could not connect: ' . mysqli_error($con)); } // 选择数据库 mysqli_select_db($con,"test"); // 设置编码,防止中文乱码 mysqli_set_charset($con, "utf8"); $sql="SELECT * FROM Websites WHERE id = '".$q."'"; $result = mysqli_query($con,$sql); echo "<table border='1'> <tr> <th>ID</th> <th>网站名</th> <th>网站 URL</th> <th>Alexa 排名</th> <th>国家</th> </tr>"; while($row = mysqli_fetch_array($result)) { echo "<tr>"; echo "<td>" . $row['id'] . "</td>"; echo "<td>" . $row['name'] . "</td>"; echo "<td>" . $row['url'] . "</td>"; echo "<td>" . $row['alexa'] . "</td>"; echo "<td>" . $row['country'] . "</td>"; echo "</tr>"; } echo "</table>"; mysqli_close($con); ?>
PHP Jquery ajax 下拉加载内容参考:
https://www.gyzth.top/article/695.html