自动完成不起作用 - PHP - Mysql - jQuery
问题描述:
When I type anything in the text box it doesn't display anything.
The search.php shows all the records if I hardcode $searchTerm='a';
Probably it is something in the jQuery I am missing.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>test</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$( "#skills" ).autocomplete({
source: 'search.php'
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="skills">skills: </label>
<input id="skills">
</div>
</body>
</html>
MY PHP (search.php) page is:
//get search term
$searchTerm = $_GET['term'];
//get matched data from skills table
$query = $db->query("SELECT * FROM skills WHERE skill LIKE '%".$searchTerm."%' ORDER BY skill ASC");
while ($row = $query->fetch_assoc()) {
$data[] = $row['skill'];
}
//return json data
echo json_encode($data);
Json
["A A EDU","A T Still","A.B.I. ","Aani", "Zane"]
Chrome Debug
答
I can´t see the send params (data) to you server call.
like this (but i haven´t right if this work):
$(function() {
$( "#skills" ).autocomplete({
source: 'search.php',
data: {
'term' : $('#skills').val()
},
type: "GET"
});
});
I prefer use a plugin to do this, in the method AJAX is possible set the results to list in field. like this:
$('#field_auto_complete').autocomplete({
lookup: function (query, done) {
$.ajax({
url: "form.php",
dataType: "json",
data: {
term : query
},
type: "GET", //you can change to POST if u need
success: function( response ){
var result = {
suggestions: response.results
};
done(result);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
$.redirect('../error');
}
});
},
onSelect: function (suggestion) {
id_ofselected = suggestion.data; //set a var with selected object
}
});
In the Php Side u have a code like this:
$digits = $_GET['term'];
$query = $db->query(SELECT name AS `value`, id AS `data`
FROM table
WHERE name LIKE '$digits%'");
while ($row = $query->fetch_assoc()) {
$data[] = $row['skill'];
}
if(isset($data[0])){
echo json_encode(array( 'results' => $cons ));
}else{
echo json_encode(array( 'results' => array());
}
I use Autocomplete Jquery plugin. See [a link] (https://github.com/devbridge/jQuery-Autocomplete)!
答
{
source: function( request, response ) {
$.getJSON( "search.php", {
term: extractLast( request.term )
}, response );
}