I am trying to get an autocomplete similiar to: Here at jquery ui in their custom example.
This instead will use an ajax call instead of hard-coded data. I have two columns that I wish to show (a value and description). As the user is typing it in, the .val() is passed to the ajax page, and it provides the suggestions. One the first column will be used for the value.
I was able to get a single column returned using a simple one-column example, but not multiple values. I am thinking it is something simple, since it is a re-hash of example code. Your help is appreciated.
<script>
$(document).ready(function() {
$('#myinputbox').autocomplete({
minLength: 4,
source: function(request, response){
var ajaxparam = $('#myinputbox').val();
ajaxparam = escape(ajaxparam);
var querystring = "?term=" + ajaxparam;
$.ajax({
url: 'ajax/jsonencode.php'+querystring,
beforeSend: function(){
alert("beforeSend");
},
async: true,
dataType: "json"
});
},
focus: function ( event,ui ){
$( "#myinputbox" ).val( ui.item.value );
return false;
},
select: function( event, ui ) {
$( "#myinputbox" ).val( ui.item.value );
return false;
}
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.value + "<br>" + item.desc + "</a>" )
.appendTo( ul );
};
});
</script>
beforeSend fires ok. If I add:
success: function(data){
alert(data);
}
...after the dataType, it properly alerts me [object Object].
The json looks like:
[
{
"value": "value1",
"desc": "Description 1"
},
{
"value": "value2",
"desc": "Description 2"
}
]
The json returned passes validation at jsonlint.
The _renderItem does not seem to work.
Any pointers or solution would be appreciated.
In your $.ajax
call, you're not specifying a success
callback:
$.ajax({
url: 'ajax/jsonencode.php'+querystring,
beforeSend: function(){
alert("beforeSend");
},
async: true,
dataType: "json"
});
Since the widget expects you to invoke the response
function to supply the suggestions, you should do something like this:
$.ajax({
url: 'ajax/jsonencode.php'+querystring,
beforeSend: function(){
alert("beforeSend");
},
async: true,
dataType: "json",
success: response
});
That assumes your data has at least a label
or value
property.
来源:https://stackoverflow.com/questions/8300908/jquery-autocomplete-custom-display-multi-column-part-2