我在显示来自 MySQL 的数据时遇到问题。我希望当我在输入字段中键入一个字母时,来自数据库的值将显示相关值。
例如,我输入A,它会显示与该产品相关的所有值。以下是我的代码 - 请提供您的建议。
<!DOCTYPE>
<html>
<head>
<script type="text/javascript">
var hxmlhttp = false;
if(window.XMLHttpRequest){
//for newer browser except ie6
xmlhttp = new XMLHttpRequest();
}else{
//for ie6 and below
xmlhttp = new ActiveXObjectt("Microsoft.XMLHTTP");
}
function askGoogleSuggest(){
var input = document.getElementById("textField");
if(input.value){
getData("select.php?qu=" + input.value,"targetDiv");
}else{
var targetDiv = document.getElementById("targetDiv");
targetDiv.innerHTML = "<div></div>";
}
}
function getData(dataSource, divId){
if(xmlhttp){
var obj = document.getElementById(divId);
xmlhttp.open("GET",dataSource,true);
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status==200){
obj.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send(null);
}
}
</script>
</head>
<h2>Langpayan Trademark</h2>
<form >
Search for <input type="text" id="textField"
name="textField" onkeyup = "askGoogleSuggest()">
</form>
<div id="targetDiv">
<p>it will display values</p>
<div></div>
</div>
</body>
选择.php
<?php
$dbc = mysqli_connect('localhost','root','black98765','activity_8a')
OR die("Cannot connect to MySql: ". mysqli_connect_error());
$display = "SELECT bug.* , product.*, hardware.hardware_brand, software.software_name, solution.solution_name, bug_hardware.*
FROM bug
JOIN product ON bug.product_no = product.product_no
JOIN bug_hardware ON bug.bug_no = bug_hardware.bug_no
JOIN hardware ON hardware.hardware_no = bug_hardware.hardware_no
JOIN software ON software.software_no = bug_hardware.software_no
JOIN solution ON solution.bug_no = bug.bug_no
WHERE product_name like '%on%'";
$re = mysqli_query($dbc, $display);
if($re){
echo "<table border=1 id='table_form'>
<tr>
<th>Product Name </th>
<th>Name of Bug </th>
<th>Brand Name</th>
<th>Operating System</th>
<th>Solution</th>
<tr>";
while($row = mysqli_fetch_assoc($re)){
echo "<tr>";
echo "<td>".$row['product_name']."</td>";
echo "<td>".$row['bug_name']."</td>";
echo "<td>".$row['hardware_brand']."</td>";
echo "<td>".$row['software_name']."</td>";
echo "<td>".$row['solution_name']."</td>";
echo "</tr>";
}
echo "</table>";
}else{
echo "Cannot fetch data";
}
?>
最佳答案
问题在对话中得到解决:
函数 getData
在 askGoogleSuggest
函数内部调用时缺少 divId
参数。
WHERE product_name like '%on%'";
行也必须更改为 WHERE product_name like '".$_GET['qu']."%'";
按照 OP 的预期行事
关于javascript - 当用户键入一个字母时,如何使用 ajax 自动完成来显示来自 MySQL 数据库的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29257038/