【发布时间】:2016-01-25 13:19:42
【问题描述】:
最近我一直在尝试编写一个系统,其中一个 php 文件读取一个充满名称的文本文件(现在我只输入 john doe)并将其显示为自动完成文本。这是我在 html 中尝试过的:
function showHint(str) {
var xhttp;
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "gethint.php?q="+str, true);
xhttp.send();
}
<!DOCTYPE html>
<html>
<body>
<h3>Start typing a name in the input field below:</h3>
<form action="">
First name: <input type="text" id="txt1" onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>
这里是 gethint.php,它起作用的部分,
<?php
// Array with names
$a = fopen("data.txt", "r") or die("Unable to open file!");
echo fread($a,filesize("data.txt"));
fclose($a);
// get the q parameter from URL
$q = $_REQUEST["q"];
$hint = "";
// lookup all hints from array if $q is different from ""
if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint = $name;
} else {
$hint .= ", $name";
}
}
}
}
// Output "no suggestion" if no hint was found or output correct values
echo $hint === "" ? "no suggestion" : $hint;
?>
【问题讨论】:
-
这里没有使用 JSON 有什么原因吗?
-
$a是目标文件,而不是数组。文件data.txt的内容是什么?采用哪种格式? -
因为我也不知道我也没见过它被使用过
-
我告诉过你,data.txt 的内容是“john doe”这几个字,而且 php 只是 2 块 php 匆忙拼凑起来的。我刚开始使用php,所以我不太擅长它