1.静态网页文件index.html :
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>无标题文档</title>
<script src="selecttest.js"></script>
</head>
<body>
<form>
请选择一个:
<select name="test" onChange="showtest(this.value)">
<option value="a">test1</option>
<option value="b ">test2</option>
<option value="c">test3</option>
</select>
</form>
<p>
<h2><div id="txtdisplay"><b>测试信息将在此处列出。</b></div></h2>
</p>
</body>
</html>
2.ajax文件 (selecttest.js脚本)
var xmlHttp
//start function showHint(str)
function showtest(str)
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("您的浏览器不支持AJAX!");
return;
}
var url="gettest.php";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
/
function stateChanged()
{
if (xmlHttp.readyState==4)
{
document.getElementById("txtdisplay").innerHTML=xmlHttp.responseText;
}
}
创建xmlHttp对象的方法///
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{// Firefox, Opera 等
xmlHttp=new XMLHttpRequest();
}
catch (e)
{ // Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
3.后台处理文件gettest.php
<?php
// HTTP/1.1
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
// HTTP/1.0
header("Pragma: no-cache");
mysql_connect("localhost","root","password") or die("连接失败");
mysql_select_db(ajax);
mysql_query("set names gbk");
$q = $_GET['q'];
$sql="SELECT * FROM test WHERE testID='".$q."'";
//$sql=$sql. "'".$q."'";
//echo $sql;
$result = mysql_query($sql);
//echo $result;
if($result)
{
echo ("<table>");
while ($arr = mysql_fetch_array($result)){
$name = $arr['name'];
$value = $arr['value'];
echo ("<tr><td><em>" .$name. "</em></td>");
echo ("<td>" .$value. "</td></tr>");
}
echo ("</table>");
}
else
{
echo "对不起,没有查找到!";
}
?>
以上三个文件可以放到同一文件夹里。