PHP、jQuery、AJAX和MySQL 数据库实例

时间:2022-07-17 12:21:14

index.html页面

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>
PHP、jQuery、AJAX和MySQL 数据库实例
</title>
</head>
<body>
<form>
Select a User:
<select name="users" onchange="showUser(this.value)">
<option value="1">
John
</option>
<option value="2">
Linda
</option>
</select>
</form>
<p>
<div id="txtHint">
<b>
User info will be listed here.
</b>
</div>
</p>
<script src="./js/jquery-1.10.2.min.js"></script>
<script src="selectuser.js"></script>
</body>
</html>

selectuser.js页面

 function showUser(str) {
$.ajax({
type:"GET",
url:"getuser.php?q="+str,
dataType:"json",
success: function(data) {
//var data = eval('(' + data + ')');
if (data.success) {
$("#txtHint").html(data.msg);
} else {
$("#txtHint").html("出现错误:" + data.msg);
}
},
error: function(jqXHR){
alert("发生错误:" + jqXHR.status);
},
});
}

getuser.php页面

 <?php
header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Methods:POST,GET');
header('Access-Control-Allow-Credentials:true');
header("Content-Type: application/json;charset=utf-8");
$q=$_GET["q"];
$con = mysql_connect('www.mytest.com', 'root', 'root');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test", $con);
$sql="SELECT * FROM MyGuests WHERE id = '".$q."'";
$res = mysql_query($sql);
$result="<table border='1'>
<tr><th>id</th><th>FirstName</th>
<th>LastName</th><th>email</th></tr>";
while($row = mysql_fetch_array($res))
{
$result=$result. "<tr><td>" . $row['id'] . "</td><td>" . $row['firstname'] . "</td><td>" . $row['lastname'] . "</td><td>" . $row['email'] . "</td></tr>";
}
$result=$result."</table>";
$data = array('msg' => $result,'success'=>true);
echo json_encode($data);
mysql_close($con);
?>