HTML代码如下:
<!DOCTYPE html> <html lang="en"> <head> <Meta charset="UTF-8"> <title>使用AJAX PHP实现与用户互动</title> <script> function myFunction(str){ var xmlhttp; if (str.length == 0) { document.getElementById("hint").innerHtml="请输入英文名字"; return; } if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); }else{ xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function(){ if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById("hint").innerHTML = xmlhttp.responseText; } } xmlhttp.open("GET","./ajaxjichu_02.PHP?username="+str,true); xmlhttp.send(); } </script> </head> <body> <form action="" method="GET"> 请输入姓名:<input type="text" name="username" onkeyup="myFunction(this.value)"> </form> <p> 建议<span id="hint"></span> </p> </body> </html>后台PHP代码如下:
<?PHP /** 使用AJAX实现与用户互动 **/ //使用名字填充数组 $a[]="Anna"; $a[]="Brittany"; $a[]="Cinderella"; $a[]="Diana"; $a[]="Eva"; $a[]="Fiona"; $a[]="Gunda"; $a[]="Hege"; $a[]="Inga"; $a[]="Johanna"; $a[]="Kitty"; $a[]="Linda"; $a[]="Nina"; $a[]="Ophelia"; $a[]="Petunia"; $a[]="Amanda"; $a[]="Raquel"; $a[]="Cindy"; $a[]="Doris"; $a[]="Eve"; $a[]="Evita"; $a[]="Sunniva"; $a[]="Tove"; $a[]="Unni"; $a[]="Violet"; $a[]="Liza"; $a[]="Elizabeth"; $a[]="Ellen"; $a[]="Wenche"; $a[]="Vicky"; $q = $_GET['username']; if (strlen($q) > 0) { $hint = ""; for ($i=0; $i < count($a) ; $i++) { if (strtolower($q) == strtolower(substr($a[$i],strlen($q)))) { if ($hint == "") { $hint = $a[$i]; }else{ $hint = $hint.",".$a[$i]; } } } } //如果没有找到提示,则输出”没有建议“。如果找到输出正确的值 if ($hint == "") { $response = "没有建议"; }else{ $response = $hint; } //输出响应 echo $response;原文链接:https://www.f2er.com/ajax/161684.html