<?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 自动完成: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。
关于php - 将 mysql 行从 PHP 加载到自动完成 jquery 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29909435/