绑定到ajax:成功Rails

时间:2015-02-06 00:47:52

标签: javascript jquery ruby-on-rails ajax

我的Rails应用程序中有以下HTML表单:

#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 %>

我的控制器设置为使用JSON响应AJAX请求:

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

我想用我的客户端Javascript处理响应,因此我试图绑定到ajax:success事件,如下所示:

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

我的服务器日志表明服务器正在响应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)

但是,我的警报永远不会触发。我想我必须错误地绑定到AJAX事件,但我不确定为什么。谢谢你的帮助。

0 个答案:

没有答案