<?php
$cuvant = (isset($_GET['cuvant']) ? $_GET['cuvant'] : '');
// the word I want to get from the search box
$sql = "SELECT cuvant FROM cautare where cuvant like'".$cuvant."%'ORDER BY nr_cautari DESC limit 0,6";
// I search for that word in a table from database
?>
<script>
$(function() {
var cuvinte=['<?php
$resursa = mysql_query($sql);
?>'];
$( "#cautare" ).autocomplete({
// #cautare is the id of the search box
source: cuvinte
});
});
</script>
我正在尝试使用jQuery创建自动完成器,并且在
index.php
页面中有此代码。我不知道如何解决此问题:当我尝试在页面上搜索内容时,什么都没有发生。 最佳答案
假设您正在使用jQuery Autocomplete:https://jqueryui.com/autocomplete/
我相信包含值的变量必须是有效的JSON。即使执行mysql_fetch_assoc()也会返回一个php数组,每一行看起来都像这样:
array(
'cuvinte' => "something"
);
因此,假设您的查询返回了多行,我认为您需要执行以下操作:
<script>
$(function() {
var cuvinte=
<?php
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
$resursa[] = $row['cuvant'];
}
echo json_encode($resursa);
?>;
$( "#cautare" ).autocomplete({// #cautare is the id of the search box
source: cuvinte
});
});
</script>
基本上,这将获取查询结果,循环遍历所有行,并构建一个临时数组。最后一步是获取该数组,然后让PHP将其转换为json。