写这篇文章有点厚无耻了,因为这是从学习网站上扒下来的,不过我也不在乎了,,就当写给自己看的。。高手路过就行了。 如果有看不惯的,可以去www.runoob.com或www.w3school.com.cn 去看下php与ajax的交互
再次声明一下,此篇功能主要是通过ajax异步动态响应数据
数据表:
对应的sql语句(给了这个再测试的话就更方便了):
--
-- 表的结构 `user`
--
CREATE TABLE IF NOT EXISTS `user` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`FirstName` varchar(24) NOT NULL,
`LastName` varchar(24) NOT NULL,
`Age` int(11) NOT NULL,
`Hometown` varchar(100) NOT NULL,
`Job` varchar(120) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;
--
-- 转存表中的数据 `user`
--
INSERT INTO `user` (`id`, `FirstName`, `LastName`, `Age`, `Hometown`, `Job`) VALUES
(1, 'Peter', 'Griffin', 41, 'Quahog', 'Brewery'),
(2, 'Lois', 'Griffin', 40, 'Newport', 'Piano Teacher'),
(3, 'Joseph', 'Swanson', 39, 'Quahog', 'Police Officer'),
(4, 'Glenn', 'Quagmire', 41, 'Quahog', 'Pilot');
然后就是test.html 前端页面内容
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here.</b></div>
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for 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","test.php?q="+str,true);
xmlhttp.send();
}
</script>
</body>
</html>
提交到test.php页面,对应的处理(主要是通过get获取id查询对应的记录遍历返回的)
<?php
/**
* Created by PhpStorm.
* User: zhangqh
* Date: 2015/5/4
* Time: 9:50
*/
header('Content-Type:text/html; charset=utf-8');
$q=$_GET["q"];
$con = mysqli_connect('localhost','root','','test');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM user WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td>" . $row['Hometown'] . "</td>";
echo "<td>" . $row['Job'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con); // 关闭数据库连接
功能效果:
写到最后,推广下一个不错的分享平台:http://www.techshare100.com/,欢迎大家加入