我正在尝试使用 jQuery UI 自动完成小部件,但没有成功。没有提供匹配列表。
我的脚本如下:
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css">
<script src="./jquery-1.11/jquery-1.11.1.min.js"></script>
<script src="./jquery-ui-1.11.1/jquery-ui.min.js"></script>
<script>
$("#tags").autocomplete({
source: function( request, response ) {
$.ajax({
url: "testAJAX.php",
type: "POST",
dataType: "json",
data: {term: request.term},
success: function(data) {
response(data);
}
});
}
});
</script>
</head>
<body>
<input type="text" id ="tags" />
</body>
</html>
在服务器上我的 PHP 代码如下:
<?php include "dbConnect.php";
header('Content-type: application/json');
$q=$_POST["term"];
$sql="SELECT name, id as value, id FROM sample WHERE id LIKE '".strtoupper($q)."%';";
$result = mysqli_query($con, $sql);
$rows = array();
while($r = mysqli_fetch_array($result)) {
$rows[] = $r;
}
$json = json_encode($rows);
echo $json;
我已经使用以下 JQuery 脚本检查了 AJAX 和 JSON 是否正常工作,该脚本确实输出 php.ini 中的值。
<script>
$(document).ready(function(){
$('#path').keyup(function(){
var t = $('#path').val();
$.ajax({
type: "POST",
url: "testAJAX.php",
data: {term: t},
dataType: 'json',
success: function( data ) {
$('#tags').html('');
for (var i in data) {
$('#tags').append(data[i].value + '<br/>');
}
}
});
});
});
</script>
</head>
<body>
<input type="text" id="path" />
<div id="tags">
</div>
</body>
</html>
最佳答案
我已经解决了;我没有将自动完成功能放在 $(function(){}) block 中。
所以应该是:
$(function(){
$("#tags").autocomplete({
source: function( request, response ) {
$.ajax({
url: "testAJAX.php",
type: "POST",
dataType: "json",
data: {term: request.term},
success: function(data) {
response(data);
}
});
}
});
});
关于jquery-ui - 将 jQuery 自动完成与 AJAX 和 JSON 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26511728/