我有一个使用远程数据源的自动完成功能。我试图缓存它,就像在http://jqueryui.com/autocomplete/#remote-with-cache中一样。
不幸的是,有些东西不起作用,但在 Chrome 开发者面板中没有显示任何错误。
这是代码:
<script>
$(function() {
var cache = {};
$( "#search" ).autocomplete({
minLength: 2,
source: function( request, response ) {
var term = request.term;
if ( term in cache ) {
response( cache[ term ] );
return;
}
$.getJSON( "suggest.php", request, function( data, status, xhr ) {
cache[ term ] = data;
response( data );
});
});
$.ui.autocomplete.prototype._renderItem = function (ul, item) {
item.label = item.label.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + $.ui.autocomplete.escapeRegex(this.term) + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.label + "</a>")
.appendTo(ul);
};
});
</script>
和html:
<form method='get' action='search.php'>
<input type='text' name='q' placeholder='Search' id="search" autocomplete="off"/>
<input type='submit' value=''>
</form>
和PHP:
<?php
$db = new PDO('mysql:host=localhost;dbname=gjpages', 'root', 'mysql96');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (!isset($_GET['term'])) {
header('HTTP/1.0 400 Bad Request');
echo 'Missing term parameter in request';
exit();
}
$queryString = strtolower($_GET["term"]);
$query = $db->prepare("SELECT name FROM company WHERE name LIKE :qs" . " UNION SELECT cat AS name FROM cat WHERE cat LIKE :qs" . " UNION SELECT subcat AS name FROM subcat WHERE subcat LIKE :qs " . " LIMIT 4");
$query->execute(array(':qs' => $queryString . '%'));
$query->setFetchMode(PDO::FETCH_NAMED);
$result = array_map(function($row) {
return array('label'=>$row['name'],'value'=>$row['name']);
}, $query->fetchAll());
header('Content-Type: application/json');
echo(json_encode($result));
?>
php 工作正常,是 javascript 有问题(我相信)。有什么问题?
感谢您的任何帮助!