1
我有一個使用遠程數據源的自動完成功能。我試圖緩存它,就像在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 (我相信)。有什麼問題?
感謝您的幫助!
你有沒有嘗試在你的JavaScript和測試中放置斷點? – doublesharp
自動完成功能是根本不工作還是隻是緩存不工作?如果根本沒有工作,可能是$ .getJSON()中的請求需要{term:request.term} – samazi