简体   繁体   中英

jquery-autocomplete with json array

I was wondering how I would be able to get this working? I've read the demo files, but I'm curious if there is a way to make it work like this. I've got one php file that is something like this

$query = "SELECT DISTINCT City FROM Locations ORDER BY City";
foreach($DBH->query($query) as $row)
{
    $array[] = $row['City'];
}
echo json_encode($array);

and some js

$('.searchbox').autocomplete('test.php', {minChars: 3,});

When I test it, I type in three letters, and instead of suggestions, I get the whole json array. I know that it's possible for this jquery-autocomplete to work with local data, but I just don't know how. https://github.com/dyve/jquery-autocomplete/ is the source, by the way.

When you provide your url 'test.php' as a source for the autocompletion, your page must compute the names finishing by the provided 'term' request parameter.

From the documentation :

When a String is used, the Autocomplete plugin expects that string to point to a URL resource that will return JSON data. It can be on the same host or on a different one (must provide JSONP). The Autocomplete plugin does not filter the results, instead the request parameter "term" gets added to the URL, which the server-side script should use for filtering the results. The data itself can be in the same format as the local data described above.

That means you must use the term request parameter in your SQL query to filter the results, for example

$query = "SELECT DISTINCT City FROM Locations where City like '".$term."%' ORDER BY City";

The docs say you should set a remoteDataType option whose value is json if your backend is returning a JSON Array:

remoteDataType (default value: false)

If this is set to 'json', the autocompleter expects a JSON array from the server. Any other settings, it defaults to the native text format using lineSeparator and Cellseparator (see below).

Eg

$('.searchbox').autocomplete('test.php', {
  minChars: 3,
  remoteDataType: 'json'
});

Also, your server-side query should make use of the q parameter that the autocompleter sends in the GET to only return the results that match what has been typed in.

将您的输入文本作为GET变量发送到test.php文件,并使用该变量将过滤器应用于您的查询。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM