Dynamically send data and receive data in jQuery autocomplete
I am using jQuery's autocomplete plugin to fill the textbox element. I want the data to be coming from an API call whenever a word is entered in the textbox. There is no predefined array to be passed to the autocomplete function, its dynamically generated from a PHP script. The code that I am using,
$(document).ready(function(){
$("#textbox").autocomplete("myurl.php");
});
t开发者_开发技巧he PHP script takes a key(i.e $__GET['key']
) as response value, and on the basis of that queries the database an gives a JSON out put.
But this is not working, how can I send the key value to the PHP script and get the JSON return value and populate my autocomplete element?
According to this page: http://docs.jquery.com/Plugins/Autocomplete/autocomplete#url_or_dataoptions, your PHP script needs to take $_GET['p']
as the input text and $_GET['limit']
as the max number of entries. If I understand correctly, your script is looking for the 'key' parameter, when it should be looking for the 'p' parameter.
It also says that the response should be each word on a new line, so rather than passing as JSON, you would need to echo "$word\n";
for each word from your database.
Alternatively, if you're set on using JSON, you could load the data using something like the following JQuery:
<script type="text/javascript">
function getData( keyTxt ) {
// Send GET request through AJAX
$.get( 'myurl.php',
// Set up your query params
{key:keyTxt},
// Callback for when the datais returned
function( data ) {
// Assuming your PHP puts returns JSON containing the "txt" array
// Convert the array of words into a space-delimited string
completeData = data.txt.join( ' ' );
// Run autocomplete.
$('textbox#textboxID').autocomplete( completeData )
},
// Tell JQuery you're returning json
'json');
</script>
Your PHP would take in the 'key' parameter, query your database and then use json_encode( )
on the array of words called 'txt'.
AFAIK the parameter you recieve in your PHP script has the key "q" (i.e. $search = $_GET['q'];
)
See http://docs.jquery.com/Plugins/Autocomplete/autocomplete#url_or_dataoptions for details.
精彩评论