1

私のindex.html.erbには、Ajax経由で送信するフォームがあります(私は思う):remote => true

<%= form_tag locations_path, :method => :get, :remote=>true  do %>
  <p>
    <%= text_field_tag :location, params[:location] %>
    <%= submit_tag "Search Near", :name => nil %>
  </p>
<% end %>

index アクションでは、json 経由で @locations を返すように設定するように配置されています

def index
     if params[:location].present?
      @locations = Location.near(params[:location], 5 , :order => :distance)

    else
      @locations = Location.all
    end
     respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @locations }
    end

  end

今のところ、@locations を返すだけです (願っています)。index.html.erb のこの div で @locations の結果を取得するにはどうすればよいですか?

<div class="places">  </div>
4

2 に答える 2

1

少し異なる方法をお勧めします: .js 応答を使用します。次に、次のようになります。

#def index
#some code...
respond_to do |format|
  format.html 
  format.js
end


#index.js.erb
$('.places').html("<%= escape_javascript(render :partial => "places_list") %>");


#_places_list.html.erb
<%- @locations.each do |location| %>
  <p><%= location.name %> </p>
<%- end %>

このトピックに関するチュートリアル: http://net.tutsplus.com/tutorials/javascript-ajax/using-unobtrusive-javascript-and-ajax-with-rails-3/

于 2012-04-27T05:56:31.657 に答える
0

ajax:successJavaScriptのフォーム要素のイベントにバインドできます

長い説明については、この投稿を参照してください: Rails 3 Remote Links and Forms by Steve Schwartz

これを置き換えることもできます:

respond_to do |format|
  format.html # new.html.erb
  format.json { render json: @locations }
end

これとともに

respond_with @locations

これをコントローラーの上部に追加します。

respond_to :json
于 2012-04-27T03:03:43.010 に答える