jQuery AutoComplete,自定义返回数据 [英] jQuery AutoComplete, custom return data
问题描述
我正在尝试创建一个自动完成框,但由于返回自定义数据而出现了问题,我似乎无法将其填充到自动完成框中.
I'm trying to create an auto-complete box and have been having problems due to returning custom data, I cannot seem to get it to populate the autocomplete box.
这是数据(JSON):
This is the data (JSON):
[{"user_id":"1","user_name":"jarru"},{"user_id":"2","user_name":"harryq"},{"user_id":"3","user_name":"sleet"}]
这是我正在使用的javascript:
And this is the javascript I'm using:
<script type="application/javascript">
$(document).ready(function(){
$("#add_email_user").autocomplete({
source: baseurl+"users/ajax/users/",
dataType: 'json',
success: function(data) {
console.log("asd");
response($.map(data, function(item) {
return {
label: item.user_name,
value: item.user_id
}
}));
}
});
});
</script>
当我使用此代码时,什么都没有发生,大约3像素的下拉列表中没有任何内容.正在正确请求数据(由FireBug控制台报告),但是下拉列表中没有填充任何数据.
When I use this code, nothing happens, there is about a 3px dropdown with nothing in it. The data is being requested properly (as reported by FireBug console) but nothing is populated into the dropdown.
推荐答案
您需要做的是提供自己的_renderItem
函数. API中的示例向您展示了如何做到这一点.您还可以查看插件的源代码,以了解其正常工作.
What you need to do is provide your own _renderItem
function. This example in the API shows you how to do just that. You can also take a look at the source code of the plugin to see how it's done normally.
$( "#project" ).autocomplete({
minLength: 0,
source: projects,
focus: function( event, ui ) {
$( "#project" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( "#project" ).val( ui.item.label );
$( "#project-id" ).val( ui.item.value );
$( "#project-description" ).html( ui.item.desc );
$( "#project-icon" ).attr( "src", "images/" + ui.item.icon );
return false;
}
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
.appendTo( ul );
};
这篇关于jQuery AutoComplete,自定义返回数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!