2013-05-09 60 views
0

所以,我剛剛發現select2。真棒。現在我想弄清楚如何使用它,服務器端與Ajax/JSON。我所見過的所有例子都顯示了使用select2與JSONP從外部源檢索數據。我覺得如果從本地模特打電話,這應該會更容易,不是嗎?我會正確地對待這個問題。 json返回一個值,但搜索框不自動完成,它保持空白。select2 AJAX'd to model,configuration

查看HTML:

<%= form_tag request_pal_path, remote: true do %> 
    <%= hidden_field_tag :email, nil, class: 'ui-corner-all' %> 
    <%= submit_tag "Send request", class: 'button' %> 
<% end %> 

,並呼籲它的一些JS:

$(document).ready(function() { 
    $("#find_user #email").select2({ 
    width: '400px', 
    placeholder: "Find user...", 
    minimumInputLength: 1, 
    multiple: false, 
    id: function(obj) { 
     return obj.id; // use slug field for id 
    }, 
    ajax: { // instead of writing the function to execute the request we use Select2's convenient helper 
     url: "/users", 
     dataType: 'json', 
     data: function (term, page) { 
     return { 
      q: term, // search term 
      page_limit: 10 
     }; 
     }, 
     results: function (data, page) { // parse the results into the format expected by Select2. 
     // since we are using custom formatting functions we do not need to alter remote JSON data 
     return {results: data}; 
     } 
    }, 
    formatResult: FormatResult, 
    formatSelection: FormatSelection, 
    escapeMarkup: function (m) { return m; } 
    }); 

}) 

function FormatResult(user) { 
    return '<div>' + user.name + '</div>'; 
} 

function FormatSelection(user) { 
    return user.name; 
} 

都到控制器,user index action

def index 
    @find = User.where('name LIKE ?', "%#{params[:q]}%") 
    @users = @find.where('id NOT IN (?)', current_user.id).order('random()').page(params[:page]).per(100) 
    @title = "Potential pals" 
    respond_to do |format| 
    format.html 
    format.js { 
     @find = @find 
     @users = @users 
    } 
    format.json { @find } 
    end 
end 

,我做了一個以.json文件因爲它迴應(不知道這是否是必要的):

<% @find.each do |user| %> 
    <%= user.name %> 
<% end %> 

因此,json在某種程度上正在工作。如果我查看開發人員控制檯,它將顯示來自http://localhost:3000/users.json?q=tay或任何的響應,並且它會返回單個值,對於Taylor(在該實例中)。但是當我在select2搜索框內搜索時,它只是旋轉並旋轉,沒有結果。沒有控制檯錯誤,所以這很好,哈。思考?謝謝!

回答

1

我想問題出在你的.json文件中,因爲select2需要json數組或json對象。嘗試刪除它並以format.json { render json: @find.to_json }迴應。其他代碼對我來說似乎沒問題。

+0

這給了我一個關於模板丟失的錯誤。使用{:locale => [:en],:formats => [:json],:handlers => [:erb,:builder,:coffee]}缺少模板用戶/索引,應用程序/索引。搜索:*' – Dudo 2013-05-09 16:29:08

+0

這確實做到了!我結合了你們兩個......'format.json {render json:@find}'。我太親近了,哈哈。 – Dudo 2013-05-09 16:43:13

+0

是的,我忘了提交json:',對不起。很高興你成功了。 – 2013-05-09 18:43:32

2

的選擇2插件預計JSON數據格式如下:

[ { "text": "Taylor", "id": 1 }, { "text" : "Tailor", "id": 2 }, ...] 

因此,你需要在你的用戶模型text更換name轉換時JSON:

def as_json(*args) 
    super.tap { |hash| hash["text"] = hash.delete "name" } 
end 

,然後在索引方法:

def index 
    @find = User.where('name LIKE ?', "%#{params[:q]}%") 
    @users = @find.where('id NOT IN (?)', current_user.id).order('random()').page(params[:page]).per(100) 
    @title = "Potential pals" 
    respond_to do |format| 
    format.html 
    format.js { 
     @find = @find 
     @users = @users 
    } 
    format.json { render json: @find, :only => [:text, :id] } # might be :name here ? 
    end 
end 

你不需要查看JSON。

+0

只有當您使用formatResult的默認實現時,select2纔會使用'{id:...,text:...}'格式,如果您使用自己的函數,則可以提供任何您想要的格式。 – 2013-05-09 16:10:09

+0

是的,沒有必要做所有的事情,但'渲染'是票。謝謝!有一個upvote =) – Dudo 2013-05-09 16:43:50