PHP、jQuery、AJAX和MySQL 数据库实例
index.html页面
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="utf-8"> 5 <title> 6 PHP、jQuery、AJAX和MySQL 数据库实例 7 </title> 8 </head> 9 <body> 10 <form> 11 Select a User: 12 <select name="users" onchange="showUser(this.value)"> 13 <option value="1"> 14 John 15 </option> 16 <option value="2"> 17 Linda 18 </option> 19 </select> 20 </form> 21 <p> 22 <div id="txtHint"> 23 <b> 24 User info will be listed here. 25 </b> 26 </div> 27 </p> 28 <script src="./js/jquery-1.10.2.min.js"></script> 29 <script src="selectuser.js"></script> 30 </body> 31 </html>
selectuser.js页面
1 function showUser(str) { 2 $.ajax({ 3 type:"GET", 4 url:"getuser.php?q="+str, 5 dataType:"json", 6 success: function(data) { 7 //var data = eval('(' + data + ')'); 8 if (data.success) { 9 $("#txtHint").html(data.msg); 10 } else { 11 $("#txtHint").html("出现错误:" + data.msg); 12 } 13 }, 14 error: function(jqXHR){ 15 alert("发生错误:" + jqXHR.status); 16 }, 17 }); 18 }
getuser.php页面
1 <?php 2 header('Access-Control-Allow-Origin:*'); 3 header('Access-Control-Allow-Methods:POST,GET'); 4 header('Access-Control-Allow-Credentials:true'); 5 header("Content-Type: application/json;charset=utf-8"); 6 $q=$_GET["q"]; 7 $con = mysql_connect('www.mytest.com', 'root', 'root'); 8 if (!$con) 9 { 10 die('Could not connect: ' . mysql_error()); 11 } 12 mysql_select_db("test", $con); 13 $sql="SELECT * FROM MyGuests WHERE id = '".$q."'"; 14 $res = mysql_query($sql); 15 $result="<table border='1'> 16 <tr><th>id</th><th>FirstName</th> 17 <th>LastName</th><th>email</th></tr>"; 18 while($row = mysql_fetch_array($res)) 19 { 20 $result=$result. "<tr><td>" . $row['id'] . "</td><td>" . $row['firstname'] . "</td><td>" . $row['lastname'] . "</td><td>" . $row['email'] . "</td></tr>"; 21 } 22 $result=$result."</table>"; 23 $data = array('msg' => $result,'success'=>true); 24 echo json_encode($data); 25 mysql_close($con); 26 ?>