【发布时间】:2019-09-08 12:33:47
【问题描述】:
我使用 PHP 和 jQuery 创建了一个自动建议搜索框。提示用户插入名字和姓氏以查找存在于我的数据库中的某人,该表位于名为customers 的表中。表 customers 包含 2 列,first_name 和 last_name。
当您输入名字时,我的搜索工作正常,但在按空格移动并输入姓氏后没有给出任何结果。按下空格键时似乎出现了整个问题。知道如何解决吗?
$(document).ready(function($){
$("#customers").autocomplete({
source: "fetch_customers.php?cc=<?php echo $agencyid; ?>",
minLength: 2,
select: function(event, ui) {
var code = ui.item.id;
if (code != '#') {
location.href = '/view-customer/' + code;
}
},
open: function(event, ui) {
$(".ui-autocomplete").css("z-index", 1000);
}
});
});
<?php
$countrycode1 = $_GET['cc'];
$term = trim(strip_tags($_GET['term']));
$term = preg_replace('/\s+/', ' ', $term);
$a_json = array();
$a_json_row = array();
$a_json_invalid = array(array("id" => "#", "value" => $term, "label" => "Only letters and digits are permitted..."));
$json_invalid = json_encode($a_json_invalid);
if ($data = $conn->query("SELECT id, first_name, last_name FROM customers WHERE agency_id='$countrycode1' AND (first_name LIKE '%$term%' OR last_name LIKE '%$term%') ORDER BY first_name , last_name"))
{
while($row = mysqli_fetch_array($data))
{
$firstname = htmlentities(stripslashes($row['first_name']));
$lastname = htmlentities(stripslashes($row['last_name']));
$code = htmlentities(stripslashes($row['id']));
$a_json_row["id"] = $code;
$a_json_row["value"] = $firstname.' '.$lastname;
$a_json_row["label"] = $firstname.' '.$lastname;
array_push($a_json, $a_json_row);
}
}
/* jQuery wants JSON data */
$json = json_encode($a_json);
print $json;
flush();
$conn->close();
【问题讨论】:
-
用 concat 函数改变查询会有帮助吗?
-
您应该将
$term拆分为 ' ' 并使用单独的值查询first_name、last_name。或者您应该使用更复杂的查询来查询您的数据库:获取包含合并值first_name + ' ' + last_name的列,然后将其与$term进行比较。 -
任何示例代码可以帮助我吗?
-
尝试替换 $term = preg_replace('/\s+/', ' ', $term); with $term = preg_replace('/\b[\w-]+\b/', ' ', $term);
-
@hans-konig,不,那不行。
标签: php jquery autocomplete