这例子是类似自动补全框,可以根据输入关键字即时匹配相关字符并显示出来。就差点css而已了~
新建文件【 AJAX and php.html】
<html>
<head>
<script type="text/javascript">
function showHint(str) {
if (str.length == 0) { // 当输入字符长度为0时 显示 ""
document.getElementById('txtHint').innerHTML = "";
return;
}
if (window.XMLHttpRequest) {
// IE+7. Firefox, Chrome, Opera, Safari 浏览器执行的代码
xmlhttp = new XMLHttpRequest(); // 创建XMLHttpRequest对象
} else {
// IE6, IE5 浏览器执行的代码
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// 创建在服务器响应就绪时执行的函数
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
// url末端 参数q包含输入内容
xmlhttp.open("GET", "gethint.php?q=" + str, true);
// 向服务器上的文件发送请求
xmlhttp.send();
}
</script>
</head>
<body>
<p><b>在文本框中输入一个姓名:</b></p>
<form action="">
姓名:<input type="text" onkeyup="showHint(this.value)">
</form>
<p>返回值:<span id="txtHint"></span></p>
</body>
</html>
新建文件【 gethint.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";
######### 将数据库中的数据也添加到 $a[] 列表中
//gbk 转 utf-8
// function enc($c){
// return iconv('gbk','utf-8',$c);
// }
// $conn = odbc_connect("myAccess", "", "");
// $sql = "select Name from Dang";
// $rs = odbc_exec($conn, $sql);
// while (odbc_fetch_row($rs)) {
// // enc函数用于调节字符类型,防止乱码
// $a[] = enc(odbc_result($rs, "Name"));
// }
##########
// 从请求URL地址中获取 q 参数
$q = $_GET["q"];
// 如果 q > 0 查找是否有匹配的字符串
if (strlen($q) > 0) {
$hint = "";
for ($i = 0; $i < count($a); $i++) {
// strtolower 将大写转换成小写 从 a 中截取和 b 长度相同的字符串 并比较是否相等,相等则将a赋给hint
if (strtolower($q) == strtolower(substr($a[$i], 0, strlen($q)))) {
if ($hint == "") {
$hint = $a[$i];
} else {
$hint = $hint . " , " . $a[$i];
}
}
}
}
// 如果没有匹配值设置输出为 "no suggestion"
if ($hint == "") {
$response = "No Suggestion";
} else {
$response = $hint;
}
//输出返回值
echo $response;
// print_r($a);
?>
此时目录:
|-AJAX and php.html
|-gethint.php
内容仅供参考~
PHP相对基础的内容要写的到这就已经差不多了,之前写的也都是很基础的,https://github.com/LSL-Git/PHP-test 这里是我练习的所有例子~