【问题标题】:JSON for JQueryUI autocomplete - Rails用于 JQueryUI 自动完成的 JSON - Rails
【发布时间】:2015-07-16 07:59:21
【问题描述】:

我正在处理一个自动完成表单字段,并且在格式化我想要传递给它的 JSON 时遇到了一些问题。我正在使用 ID 字段进行自动完成,尽管 JSON 返回如下:

{"users":["12345","23456","34567", ... ]}

据我了解,我需要一个用于 JQuery 自动完成的数据数组——我正在使用它——尽管我似乎无法丢失围绕它的哈希值。有什么建议吗?或者如果我在其他地方出错了,指导会很棒!

这是其他相关代码:

JS

$(document).on('ready page:load', function(){
    $( "#user_****Id" ).autocomplete({
      source: $('#user_****Id').data('autocomplete-source')
    })
})

表格(haml)

= simple_form_for [:admins, @user] do |f|
  ...
  = f.input :****Id, input_html: { data: { autocomplete_source: new_admins_user_path } }
  ...

控制器

def new
    @hospitals = Hospital.all
    @hospitals_autocomplete = @hospitals.map(&:id)

    respond_to do |format|
      format.html
      format.json {render json: @hospitals_autocomplete}
    end
  end

谢谢大家 - 史蒂夫。

【问题讨论】:

  • 我不知道 haml 以任何方式插入 jquery。 data-autocomplete-source 中有什么内容?看起来应该是字符串,而不是数组

标签: jquery ruby-on-rails ruby jquery-ui autocomplete


【解决方案1】:

如果您正在寻找自动完成功能,我会推荐Jquery TokenInput,我自己使用过它,而且它易于设置。让我给您举个例子:-

在您的表单字段中

<% form_for(@user,:url=>new_user_path) do |f|%>

//other input text and text area fields
//autocomplete field to add tag to user and also show existing tags
//suppose this field is user_tag_list
<%= f.text_field :tag_list, "data-pre" => @user.tags.map(&:attributes).to_json  %>
<%end%>

在js代码中:-

//activate the autocomplete text field(user_tag_list) and call ajax to return json from the controller
   $("#user_tag_list").tokenInput("/users/show_user_tags.json", {
    crossDomain: false,
    placeholder: "Add your Favorite user tags",
    prePopulate: $("#user_tag_list").data("pre"),
    theme: "facebook",
    hintText: "Tag this user with your fav tags",
    noResultsText: "Well,search for you fav tags",
    searchingText: "here it comes <i class='fa fa-spinner fa-spin fa-lg'></i>",
    tokenLimit:3,
    //add title to search on basis of title on form submit
    tokenValue: 'name',
    resultsLimit:10,
    resultsFormatter: function(item){ return "<li><p><span style='font-size:1em !important;'><b>" + item.name + "</b></span></p></li>" },
    tokenFormatter: function(item) { return "<li><p>" + item.name + "</p></li>" },
    preventDuplicates: true
  });

控制器代码...在用户控制器中调用 show_user_tags

def show_user_tags
  @tags = UserTag.where("title like ?", "#{params[:q].capitalize}%")
  @tags = @tags.map do |c|
      { :id => c.id,:name => c.title}
    end   
    respond_to do |format|
      format.html
      format.json { render :json => @tags }
    end
 end 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-08
    • 1970-01-01
    • 2014-04-09
    • 1970-01-01
    • 1970-01-01
    • 2014-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多