你可以试试这个(下面这段代码没有进行测试,但它应该工作)
HTML页面
Select a User:
Peter Griffin
Lois Griffin
Glenn Quagmire
Joseph Swanson
Select an age:
39
40
41
42
Java的脚本代码:
var xmlhttp;
function showUser(str,age)
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url="getuser.php";
url=url+"?q="+str+"&a="+age;
url=url+"&sid="+Math.random();
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function stateChanged()
{
if (xmlhttp.readyState==4)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
PHP页面为
$q=$_GET["q"];
$a=$_GET["a"];
$con = mysql_connect('localhost', 'peter', 'abc123');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ajax_demo", $con);
$sql="SELECT * FROM user WHERE id = '".$q."' and age='".$a."'";
$result = mysql_query($sql);
echo "
Firstname | Lastname | Age | Hometown | Job |
---|
while($row = mysql_fetch_array($result))
{
echo "
";echo "
" . $row['FirstName'] . "";echo "
" . $row['LastName'] . "";echo "
" . $row['Age'] . "";echo "
" . $row['Hometown'] . "";echo "
" . $row['Job'] . "";echo "
";}
echo "
";mysql_close($con);
?>