jQuery UI AutoComplete parsing data from variable
I am attempting to use the jQuery UI Autocomplete, and just can't seem to put two and two together.
I have a php page that is used for all json data requests. I use a switch statement to determine which function to fire off when a request is made, using post to pass this data to the php page, ie; "AutoComplete" is passed to the page, which then tells it to retrieve a particular table from my database, then encode it into json.
The da开发者_如何转开发ta is formatted as such: ["1":"Email", "2":"Hosting"] and so forth. There are a variable number of items in the json data, but always with the key=>value pair. I need the key to be the value of the field, and the value to be displayed in the autocomplete list. (The data order can be reversed if need be, this is just an example).
I don't need or want the autocomplete feature to hit this database every time someone types some characters in the box, so I'm attempting to just generate a static list of the options needed for this field and assign these to a javascript object for use with autocomplete().
function myFunction (DataType, ID) {
$j.ajax({
type: 'POST',
cache: 'false',
url: 'json.php',
data: {jsonFunction:DataType},
success: function(data){
$j(ID).autocomplete({ source: [data] });
}
});
};
The function is then called in my document.ready() function:
myFunction ("AutoComplete", "input#Type");
So what I need is to be able to create a variable from an ajax request that autocomplete can use as its options. I just can't figure out how to get this to work! I've tried several different methods to no avail, including parsing through the data with several examples I've seen here and elsewhere. The documentation for the ui autocomplete states that you can use an array with key value pairs, but it just doesn't like my data no matter how its formatted.
I'm missing something obvious, I'm sure.
Hmm, it's really bad practice, but you could use eval(). Just use javascripts quick-object notation (the braces like jQuery uses)
A better solution - cache your database (assumption) queries
Have you tried setting the dataType
option of the ajax call to json? See the doc here: http://api.jquery.com/jQuery.ajax/
精彩评论