如何从Project.all等模型中获取所有项目的列表,并将其中的所有project.name移动到javascript中列出,然后使用Jquery UI Autocomplete打印出来
Link to Jquery UI Autocomplete
$( " #tags " ).autocomplete({
source: function(request, response){
//pass request to server
$.ajax({
url: "/projects/project_list",
dataType: "json",
data: {
style: "full",
maxRows: 12,
term: request.term
},
minLength: 1,
select: function( event , ui ) {
log( ui.item ?
ui.item.value : + this.value );
}
});
答案 0 :(得分:1)
认为你可能正在寻找这样的东西:
def project_list
list=Project.all.map{|i|[i.name,i.id]}
arr= [["No project",0]].concat(list.sort{|a,b| a[0]<=>b[0]}).to_json
render :json =>arr
end
然后,您需要从js
中调用此方法 $("#some_input_id").autocomplete({
source: function(request, response){
//pass request to server
$.ajax({
url: "/projects/project_list",
dataType: "json",
data: {
style: "full",
maxRows: 12,
term: request.term
},
success: function( data ) {
#do stuff here
}
});
});
以下是一些相对完整的例子,可以生成一个自动完成的机场列表
$("#airport, #station").autocomplete({
delay: 1000,
search: function(event,ui){
tag = event.target.id
},
source: function(request, response){
//pass request to server
$.ajax({
url: "/tags/"+ tag +"/list",
dataType: "json",
data: {
style: "full",
maxRows: 12,
term: request.term
},
success: function( data ) {
response( $.map( data, function( item ) {
if (tag == "airport"){
return {
label: item.airport.fd_name
}
}
else
{
return {
label: item.station.fd_name
}
}
}));
}
});
},
minLength: 2,
open: function( event, ui ) {
stripe($(this));
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
这是相关的控制器代码:
def list
@tags= params[:tagclass].titleize.constantize.where("fd_name ilike ? ",params[:term]+"%").order('fd_name')
render :json => @tags.to_json(:only=>[:fd_code, :fd_name]), :layout=>false
end
`