我想为大约 100 万个可能植物名称的数据库中的表单输入元素提供自动完成功能。
我对 javascript 的了解有限,经过各种尝试,我从 w3Schools ( https://www.w3schools.com/howto/howto_js_autocomplete.asp ) 复制并粘贴了一些代码,我只是部分理解了这些代码。
w3Schools 示例使用了一个包含大约 200 个国家名称的硬编码数组,称为countries. 我将此数组的分配更改为对 SQLite 数据库的 PHP 查询,称为wcvp(世界维管植物清单。请参阅:https ://wcvp.science.kew.org/和http://sftp.kew.org/pub/数据存储库/WCVP/)。
当我将查询限制为大约 39000 个不同的属名时,自动完成功能似乎工作得很好。当我更改查询以在数据库中包含所有不同的物种和亚种(大约 110 万个)时,我只是在浏览器中得到一个空白页面。我认为行为的差异取决于所涉及的项目数量。
我很想知道更多关于为什么自动完成功能会因更大的数据集而失败,而不是仅仅花费更长的时间来工作。此外,我很想知道我可能采取的任何方法来使其应对更大的数据集。
我已经在这个问题的末尾发布了完整的代码。我添加的关键位与查询wcvp数据库和将查询结果分配给countries数组有关:
这给出了大约 39000 个结果,并且自动完成效果很好:$sql = "SELECT DISTINCT genus FROM wcvp";
这会产生大约 110 万个结果,并导致页面无法加载到我的 Firefox 浏览器中:$sql = "SELECT DISTINCT taxon_name FROM wcvp";
以下代码是我如何使用上述 SQL 查询的结果填充 JavaScript 数组:
countries = [
<?php
foreach($plantNames as $plantName){
echo "'{$plantName[0]}',";
}
?>
];
除了上面提到的我所做的添加之外,我还从 w3Schools 示例中删除了样式元素,它不会显着改变功能,但会缩短代码。完整的代码(包括上面显示的部分,没有 CSS)是:
<?php
require './sqlite/dsn.php';
$sql = "SELECT DISTINCT genus FROM wcvp";
//$sql = "SELECT DISTINCT taxon_name FROM wcvp";
$stmt = $db->prepare($sql);
$stmt->execute();
$plantNames = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h2>Autocomplete</h2>
<p>Start typing:</p>
<!--Make sure the form has the autocomplete function switched off:-->
<form autocomplete="off" action="/action_page.php">
<div class="autocomplete" style="width:300px;">
<input id="myInput" type="text" name="myCountry" placeholder="Country">
</div>
<input type="submit">
</form>
<script>
function autocomplete(inp, arr) {
/*the autocomplete function takes two arguments,
the text field element and an array of possible autocompleted values:*/
var currentFocus;
/*execute a function when someone writes in the text field:*/
inp.addEventListener("input", function(e) {
var a, b, i, val = this.value;
/*close any already open lists of autocompleted values*/
closeAllLists();
if (!val) { return false;}
currentFocus = -1;
/*create a DIV element that will contain the items (values):*/
a = document.createElement("DIV");
a.setAttribute("id", this.id + "autocomplete-list");
a.setAttribute("class", "autocomplete-items");
/*append the DIV element as a child of the autocomplete container:*/
this.parentNode.appendChild(a);
/*for each item in the array...*/
for (i = 0; i < arr.length; i++) {
/*check if the item starts with the same letters as the text field value:*/
if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
/*create a DIV element for each matching element:*/
b = document.createElement("DIV");
/*make the matching letters bold:*/
b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";
b.innerHTML += arr[i].substr(val.length);
/*insert a input field that will hold the current array item's value:*/
b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
/*execute a function when someone clicks on the item value (DIV element):*/
b.addEventListener("click", function(e) {
/*insert the value for the autocomplete text field:*/
inp.value = this.getElementsByTagName("input")[0].value;
/*close the list of autocompleted values,
(or any other open lists of autocompleted values:*/
closeAllLists();
});
a.appendChild(b);
}
}
});
/*execute a function presses a key on the keyboard:*/
inp.addEventListener("keydown", function(e) {
var x = document.getElementById(this.id + "autocomplete-list");
if (x) x = x.getElementsByTagName("div");
if (e.keyCode == 40) {
/*If the arrow DOWN key is pressed,
increase the currentFocus variable:*/
currentFocus++;
/*and and make the current item more visible:*/
addActive(x);
} else if (e.keyCode == 38) { //up
/*If the arrow UP key is pressed,
decrease the currentFocus variabe:*/
currentFocus--;
/*and and make the current item more visible:*/
addActive(x);
} else if (e.keyCode == 13) {
/*If the ENTER key is pressed, prevent the form from being submitted,*/
e.preventDefault();
if (currentFocus > -1) {
/*and simulate a click on the "active" item:*/
if (x) x[currentFocus].click();
}
}
});
function addActive(x) {
/*a function to classify an item as "active":*/
if (!x) return false;
/*start by removing the "active" class on all items:*/
removeActive(x);
if (currentFocus >= x.length) currentFocus = 0;
if (currentFocus < 0) currentFocus = (x.length - 1);
/*add class "autocomplete-active":*/
x[currentFocus].classList.add("autocomplete-active");
}
function removeActive(x) {
/*a function to remove the "active" class from all autocomplete items:*/
for (var i = 0; i < x.length; i++) {
x[i].classList.remove("autocomplete-active");
}
}
function closeAllLists(elmnt) {
/*close all autocomplete lists in the document,
except the one passed as an argument:*/
var x = document.getElementsByClassName("autocomplete-items");
for (var i = 0; i < x.length; i++) {
if (elmnt != x[i] && elmnt != inp) {
x[i].parentNode.removeChild(x[i]);
}
}
}
/*execute a function when someone clicks in the document:*/
document.addEventListener("click", function (e) {
closeAllLists(e.target);
});
}
countries = [
<?php
foreach($plantNames as $plantName){
echo "'{$plantName[0]}',";
}
?>
];
/*An array containing all the country names in the world:*/
//var countries = ["Afghanistan","Albania","Alg.......emen","Zambia","Zimbabwe"];
/*initiate the autocomplete function on the "myInput" element, and pass along the countries array as possible autocomplete values:*/
autocomplete(document.getElementById("myInput"), countries);
</script>
</body>
</html>
编辑:如果我将查询限制为 100,000 个结果$sql = "SELECT DISTINCT taxon_name FROM wcvp LIMIT 100000";(