我有以下
<form action="" method="post">
<input type="text" class="auto" name="search" autocomplete="off">
</form>
<script>
$(document).ready(function($){
$('.auto').autocomplete({
source:'connect.php',
minLength:1
});
});
</script>
和connect.php 我知道在将其输入查询之前我必须清理$ term。
if(isset($_GET['term'])) {
require "db.php";
$con = mysqli_connect("$host","$user","$password","$db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$term = $_GET['term'];
$query = "SELECT `name` FROM `products` WHERE `name` LIKE '%$term%'";
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result)) {
echo json_encode($row);
}
}
如果我在输入字段中键入M
并使用Chrome工具检查响应,我就会知道。
{&#34; 0&#34;:&#34; MacBook Pro 13英寸&#34;,&#34;名称&#34;:&#34; MacBook Pro 13英寸&#34;} {& #34; 0&#34;:&#34;的MacBook Pro 15英寸&#34;,&#34;名称&#34;:&#34; MacBook Pro 15英寸&#34;} {&#34; 0&#34;:&#34; MacBook Air 13英寸&#34;,&#34;名称&#34;:&#34; MacBook Air 13英寸&#34;} {&#34; 0&#34;:&#34; MacBook Air 11英寸&#34;,&#34;名称&#34;:&#34; MacBook Air 11英寸&#34;} {&#34; 0&#34;:&#34; iMac 21.5英寸&#34;,&#34;名称&#34;:&#34; iMac 21.5英寸&#34;} {&#34; 0&#34;:&#34; iMac 27英寸&#34;, &#34;名称&#34;:&#34; iMac 27英寸&#34;} {&#34; 0&#34;:&#34; Mac Pro四核&#34;,&#34;名称&# 34;:&#34; Mac Pro四核&#34;} {&#34; 0&#34;:&#34; Mac Pro 6-Core&#34;,&#34; name&#34;:&#34; Mac Pro 6-Core&#34;}
但是,出于某种原因,它表示“未找到任何结果&#39;在页面上,即使有吗?
答案 0 :(得分:0)
你的php脚本创建的输出是无效的json - 你必须将各个对象包装在一个数组中:
[{"0":"MacBook Pro 13-inch","name":"MacBook Pro 13-inch"}, {"0":"MacBook Pro 15-inch","name":"MacBook Pro 15-inch"}, {"0":"MacBook Air 13-inch","name":"MacBook Air 13-inch"}, {"0":"MacBook Air 11-inch","name":"MacBook Air 11-inch"}, {"0":"iMac 21.5-inch","name":"iMac 21.5-inch"}, {"0":"iMac 27-inch","name":"iMac 27-inch"}, {"0":"Mac Pro Quad-Core","name":"Mac Pro Quad-Core"}, {"0":"Mac Pro 6-Core","name":"Mac Pro 6-Core"}]
像这样修改你的PHP脚本:
$result = array();
while ($row = mysqli_fetch_array($result)) {
$result[] = $row;
}
json_encode($result);
除此之外 - 您的输出应该具有属性id,value和label,而不仅仅是“0”。