I have an autocomplete which uses a remote datasource. I tried to cache it, like in http://jqueryui.com/autocomplete/#remote-with-cache .
Unfortunately, something isn't working, but doesn't show any errors in the Chrome Developer Panel.
Here's the code:
<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>
and the html:
<form method='get' action='search.php'>
<input type='text' name='q' placeholder='Search' id="search" autocomplete="off"/>
<input type='submit' value=''>
</form>
and the 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));
?>
The php is working fine, it's the javascript that has the issue (I believe). What's the problem?
Thanks for any and all help!
SandorA comment worked.
I needed to change it to be {term: request.term} to get it working again.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.