绑定到ajax:success Rails

I have the following HTML form in my Rails app:

#views/foods/index.html.erb
<%= form_tag foods_path, remote: true, method: :get do %>
  <p>
    <%= text_field_tag :search, params[:query] %>
    <%= submit_tag "Aminoize!", name: nil %>
  </p>
<% end %>

My controller is set up to respond to the AJAX request with JSON:

#controllers/foods_controller.rb
def index
  if params[:search]
    @foods = Food.search(params[:search])
    render json: @foods
  end
end

I want to handle the response with my client side Javascript, thus I am attempting to bind to the ajax:success event like so:

#foods/views/index.js.erb
$('#search').on('ajax:success', function(data) {
  alert("This works!");
  //eventually do something with data here
});

And my server log indicates the server is responding with 200:

Started GET "/foods?utf8=%E2%9C%93&search=edamame" for 127.0.0.1 at 2015-02-05 16:38:37 -0800
Processing by FoodsController#index as JS
Parameters: {"utf8"=>"✓", "search"=>"edamame"}
Food Load (1.0ms)  SELECT "foods".* FROM "foods"  WHERE (name @@ '%edamame%')
Completed 200 OK in 21ms (Views: 0.2ms | ActiveRecord: 5.7ms)

However, my alert is never triggering. I figure I must be binding to the AJAX event incorrectly, but I am unsure why. Thanks for your help.

查看全部
weixin_33729196
weixin_33729196
2015/02/06 00:47
  • ruby-on-rails
  • ajax
  • javascript
  • jquery
  • 点赞
  • 收藏
  • 回答
    私信

0个回复