一个简单的AJAX实现

仿照w3school,做了个简单的ajax。

index.html

<!DOCTYPE html>
<html>
<head charset = "utf-8">
<script type="text/javascript">
function showHint(str) {
	var xmlhttp;
	if (str.length == 0) {
		document.getElementById("txtHint").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("txtHint").innerHTML = xmlhttp.responseText;
		}
	}
	xmlhttp.open("GET", "gethint.php?q=" + str, true);
	xmlhttp.send();
}
</script>
</head>
<body>
<h3>请在下面输入框键入字母(A - Z):</h3>
<form action="">
姓氏:<input type="text" id="txt1" onkeyup="showHint(this.value)" />
</form>
<!--txtHint是一个漂亮的hook, 同过javascript的innerHTML做替换-->
<p>建议:<span id="txtHint"></span></p>
</body>
</html>

showHint.php

<?php
//示例数组,可用数据库优化
$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";

//取得用户输入的str
$q = $_GET["q"];

//匹配判定
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];
			}
		}
	}
}

if ($hint == "") {
	$response = "找不到匹配的...";
} else {
	$response = $hint;
}

echo $response;
?>

本地测试要先搭建apache服务器,chrome,firefox,ie8均不支持本地 xmlhttp.open("GET", "gethint.php?q=" + str, true);请求。

你可能感兴趣的:(一个简单的AJAX实现)