我尝试使用jQuery-UI自动填充搜索字段,并且使用PHP作为源代码时出现问题。当我使用变量作为源时,一切正常。
JS:
$(function () {
var data = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$("#tags").autocomplete({
source: data
});
});
但是一旦我使用PHP脚本,即使它只是拥有一个数组并对其进行编码,它也不会。
JS:
$(function () {
$("#tags").autocomplete({
source: 'suggest_search.php'
});
});
suggest_search.php:
$data = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
echo json_encode($data);
我只是想弄清楚为什么,有什么建议吗?
编辑:所以原来的问题已经解决,只是一个链接问题。
现在我想从SQL获取数据,但我无法弄清楚我再次犯错的地方..
我的phpcode:
<?php
header('Content-Type: application/json');
include(scripts/db_connect.php);
$searchTerm = filter_input(INPUT_GET, 'term');
$select = mysqli_query($db_mysqli, " SELECT * FROM $db_table WHERE top_name like '%$searchTerm%'");
while ($row=mysqli_fetch_array($select))
{
$data[] = $row['top_name'];
}
echo json_encode($data);
和相关的HTML代码:
<div id="ui-widget">
<label for="tags"></label>
<input id="tags" class="search_field" type="search" name="suche" maxlength="255">
</div>
答案 0 :(得分:0)
这并不是那么简单,我真的不知道为什么,但是当你绑定到本地数组时,一个简单的数组工作,但如果你绑定到远程源,你需要给出这个结构的对象数组的结果:
{
"id":"Tetrao tetrix",
"label":"Black Grouse",
"value":"Black Grouse"
}
查看我从this page获取的结果:
https://jqueryui.com/resources/demos/autocomplete/search.php?term=rou
所以你的结果应该与那个结构相匹配才能工作,因为我找不到api docs中与数据结构相关的任何内容。
答案 1 :(得分:0)
您必须在数据源文件中使用JSON标头。
<?php
header('Content-Type: application/json');
$data = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC"
];
echo json_encode($data);
HTML文件内容;
<html>
<head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
</head>
<body>
<input id="tags">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript">
$(function() {
$( "#tags" ).autocomplete({
source: 'json.php'
});
});
</script>
</body>
</html>