【问题标题】:Rails: Using Ajax to fill Jquery AutocompleteRails:使用 Ajax 填充 Jquery Autocomplete
【发布时间】:2015-12-09 06:20:05
【问题描述】:

我在这个过程中到处插入不同的东西,但我仍然没有得到任何结果。

有时我会收到臭名昭著的额外“ 这绝对不是我的 json 文件: 无论如何,这是我的 javascript:

$('#q_name_cont').autocomplete({
url: "autocomplete/items",
dataType: 'json'
});

这是我的路线:

get 'autocomplete/items' => 'home#autocomplete_items', :defaults=>{:format=>'json'}

Controller Action(注释掉的部分是我尝试了一段时间的另一种方法):

def autocomplete_items
  # respond_to do |format|
  # format.js {render 'autocomplete_items'}
@products = Item.all.order(:name)
respond_to do |format|
  format.html
  format.json { 
    render json: @products.map {|item| item.name}
  }
end
end

在使用映射之前,我使用此视图进行渲染:

{
"items": [
<%Item.all.each do |i|%>
    { "<%=i.name%>","<%=i.name%>" },
<%#end%>
    { "value": "",        "data": "" }
]
}

我真的到处都是,尝试了很长时间才能让它发挥作用。我错过了什么?

【问题讨论】:

    标签: javascript jquery ruby-on-rails json ajax


    【解决方案1】:

    IIRC,您的 urldataType 选项在自动完成的文档中不存在。你可以试试source 选项:

    $('#q_name_cont').autocomplete({
      source: function (request, response) {
        $.ajax({
          url: "/autocomplete/items", // should be with '/'
          dataType: 'json',
          data: { query: request.term },
          success: function(data) {
            // call response to return the result to autocomplete box
            response(data);
          }
        });
      }
    });
    

    当然,这只是为了显示所有项目,如果你想像真正的自动完成框一样过滤,你应该修改控制器以根据查询过滤结果:

    def autocomplete_items
      @products = Item.all.order(:name)
      respond_to do |format|
        format.html
        format.json { 
          render json: @products
                          .where('name ILIKE ?', "%#{params[:query]}%")
                          .pluck(:name)
        }
      end
    end
    

    【讨论】:

      猜你喜欢
      • 2012-04-28
      • 2013-04-23
      • 2015-04-09
      • 2023-03-10
      • 2016-11-07
      • 2011-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多