それで、select2を発見しました。素晴らしい。今、私はそれをどのように使用するかを理解しようとしています.ajax / jsonを使用したサーバー側。私が目にするすべての例は、JSONP で select2 を使用して外部ソースからデータを取得することを示しています。ローカルモデルから呼び出すと、これはさらに簡単になるはずですよね?私はすぐに核心に行きます。json は値を返しますが、検索ボックスはオートコンプリートされず、空白のままです。
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 検索ボックス内を検索すると、回転して回転するだけで、結果はありません。コンソール エラーがないので、いいですね。考え?ありがとう!