我将自动完成功能应用于搜索框但是当我在搜索框中键入某个值时,它总是给我相同的结果。
我意识到我没有遍历数据库,这就是为什么我一直得到相同的结果
我改变了我的查询,以便我可以得到我想要的但结果仍然相同
这是我自动完成的ajax,我不确定这是正确的方法吗?但是搜索功能正在工作,除了它不显示所有数据。
function autoComplete(){
$('#keywords').autocomplete({
source: 'autoComplete.php',
minLength : 3,
select: function(event, ui) {
console.log(ui);
$('#chosenEvent').append(ui.item.value + "\n");
}
});
这是php代码
<?php
// include the file for the database connection
include_once("database_conn_getOffers.php");
function autoC($conn){
$sql = "select eventTitle from te_events_special_offers eventTitle ORDER BY eventTitle";
$rsOffer = mysqli_query($conn, $sql);
//$offer = mysqli_fetch_all($rsOffer, MYSQLI_ASSOC);
$titles = array();
while($title = mysqli_fetch_assoc($rsOffer)){
$titles[] = $title;
}
foreach ($titles as $title)
return json_encode($title);
}
echo autoC($conn)
?>
以下是我引用click here
的链接感谢您的帮助!
所以现在,我使用以下代码更改了ajax方法,它可以工作,但我仍然不知道我之前的ajax代码有什么问题。
我还删除了foreach
并添加了implode
方法
$.ajax({
method :"get",
url :"autoComplete.php"
})
.done(function(data, status, jqxhr){
var eventList;
console.log(data);
eventList = data.split(',');
$("#keywords").autocomplete({
minLength :2 ,
source : eventList,
select: function(event,ui){
console.log(ui);
}
//end autocompoete
});
});
答案 0 :(得分:1)
请尝试首先要对结果进行编码,然后我们会使用它们。同时运行此代码,而不是其他任何,并告诉我们你得到了什么(我假设你有列ID + TITLE,如果没有,请在使用前更正代码)。此外,你原始的查询似乎很奇怪 - &gt; $ sql =“SELECT eventTitle FROM te_events_special_offers eventTitle ORDER BY eventTitle”; / *检查它的粗体部分* /
加号:你应该考虑预备语句和error_reporting
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include"config.inc.php";
$mysqli = mysqli_connect("$host", "$user", "$mdp", "$db");
if (mysqli_connect_errno()) { echo "Error connecting : " . mysqli_connect_error($mysqli); }
$query = " SELECT idTitle, eventTitle FROM te_events_special_offers ORDER BY eventTitle "; /* check names used here and adapt to yours */
$stmt = $mysqli->prepare($query);
$results = $stmt->execute();
$stmt->bind_result($idTitle, $eventTitle);
$stmt->store_result();
if ($stmt->num_rows > 0) {
$events = array();
$event = array();
while($stmt->fetch()){
echo"[ $idTitle -> $eventTitle ]<br />";
$event["id"] = "$idTitle";
$event["title"] = "$eventTitle";
array_push($events, $event);
}
}
else
{ echo"[ no data ]"; }
print_r($events);
echo json_encode($events);
?>
答案 1 :(得分:0)
试试这个
$sql = "select eventTitle from te_events_special_offers eventTitle ORDER BY eventTitle";
$rsOffer = mysqli_query($conn, $sql);
$titles = array();
while($title = mysqli_fetch_assoc($rsOffer)){
$titles[] = $title;
}
return json_encode($title);