我基本上是从 w3c 学校复制这个示例,当您开始输入名称时,会添加一些建议。没有为我添加任何建议。
nameguess.html
<!DOCTYPE html>
<html lang="en-ca">
<head>
<meta charset="utf-8" />
<title>Ajaxing</title>
<script type="text/javascript">
<!--
function showHint(str)
{
var xmlhttp;
if (str.length == 0)
{
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","gethint.php?q="+str,true);
xmlhttp.send();
}
//-->
</script>
</head>
<body>
Hello.<br />
<form method="GET" action="">
Name: <input type="text" id="txt1" /><br />
Suggestions: <span id="txtHint"></span>
</body>
</html>
gethint.php
<?php
// Fill up array with names
$a[]="Anna";
//removed code to save space
$a[]="Vicky";
//get the q parameter from URL
$q=$_GET["q"];
//lookup all hints from array if length of q>0
if (strlen($q) > 0)
{
$hint="";
for($i=0; $i<count($a); $i++)
{
if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
{
if ($hint=="")
{
$hint=$a[$i];
}
else
{
$hint=$hint." , ".$a[$i];
}
}
}
}
// Set output to "no suggestion" if no hint were found
// or to the correct values
if ($hint == "")
{
$response="no suggestion";
}
else
{
$response=$hint;
}
//output the response
echo $response;
?>
我将这两个文件都位于 WAMP 的 www 文件夹中,并且正在运行虚拟服务器。