[英]how to connect jquery ui auto-complete widget with database?
upload.php的
<?php
include('lib.php');
$text = $mysqli->real_escape_string($_GET['term']);
$query = "SELECT * FROM user WHERE area LIKE (:keyword) ORDER BY id ASC
LIMIT 0, 10";
$result = $mysqli->query($query);
$json = '[';
$first = true;
while($row = $result->fetch_assoc())
{
if (!$first) { $json .= ','; } else { $first = false; }
$json .= '{"value":"'.$row['area'].'"}';
}
$json .= ']';
echo $json;
?>
area_list.js
$(function(){
var test=["red","blue","pink","Black" ,"Grey"];
$("#term2").autocomplete({
source:'<?php include upload_where.php; ?>'
});
});
HTML
<input id="term2" placeholder="e.g New Delhi, Mumbai" />
如果您认为代码正确,则可能是因为我之前没有使用过json,所以我的服务器不支持json。
您不能在javascript中包含您的php。 因此,您需要创建一个自动完成的php脚本。 在此脚本中,最好使用数组存储结果,然后使用“ json_encode”将其转换为json。
autocomplete.php:
<?php
include('lib.php');
if(true === isset($_GET['term']) && false === empty($_GET['term']))
{
$text = $mysqli->real_escape_string($_GET['term']);
$query = "SELECT * FROM user WHERE area LIKE (:keyword) ORDER BY id ASC
LIMIT 0, 10";
$result = $mysqli->query($query);
$json = array();
$first = true;
while($row = $result->fetch_assoc())
{
$json[] = $row['area'];
}
header('Content-Type: application/json');
echo json_encode($json);
}
?>
对于javascript,请使用ajax检索结果
$('#term2').autocomplete({
minChars:2,
noCache: false, //default is false, set to true to disable caching
// callback functions:
source: function( request, response ) {
$.ajax({
url: "autocomplete.php", //Correspond to PHP page
dataType: "json",
data: {term: request.term},
success: function(data) {
return data;
}
});
}
});
您使用字符串作为输入,但是确实需要一个数组作为自动完成源。
如果您不想编写ajax请求代码,并且js是由php动态生成的,则可以用以下代码替换您的代码:
$(function(){
var test=["red","blue","pink","Black" ,"Grey"];
$("#term2").autocomplete({
source:<?php include upload_where.php; ?>
});
});
但是,使用php生成js并不是一个好主意 。 因此您可以使用ThinkTank答案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.