0

それで、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 検索ボックス内を検索すると、回転して回転するだけで、結果はありません。コンソール エラーがないので、いいですね。考え?ありがとう!

4

2 に答える 2

2

select2 プラグインは、次の形式の JSON データを想定しています。

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

したがって、JSON に変換するときは、ユーザー モデルをname次のように置き換える必要があります。text

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

次に、index メソッドで次のようにします。

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のビューは必要ありません。

于 2013-05-09T15:48:37.363 に答える
1

select2 には json 配列または json オブジェクトが必要なので、問題は .json ファイルにあると思います。それを削除して、 で応答してみてくださいformat.json { render json: @find.to_json }。他のコードは私には問題ないようです。

于 2013-05-09T15:38:52.813 に答える