最近看了 ajax 解决了php局部刷新 顿时感觉好强大,所以有必要大家分享一下
http://www.runoob.com/php/php-ajax-php.html
一下代码是我用ajax向数据库插入和读出数据
index.php页面
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script>
function showHint(str)
{
if (str.length==0)
{
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","gethint.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<p><b>在输入框中输入一个姓名:</b></p>
<form>
姓名:<input type="text" οnkeyup="showHint(this.value)">
</form>
<p>返回值: <span id="txtHint"></span></p>
</body>
</html>
gethint.php页面
<?php
$q=$_GET["q"];
$con = mysqli_connect('localhost','root','','test');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
$sql="insert into test(fenshu) values ('$q')";
mysqli_query($con,$sql);
$sql2="select * from test";
$result=mysqli_query($con,$sql2);
echo "<table border='1'>
<tr>
<
<th>id</th>
<th>分数</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['fenshu'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>