普通网友 2015-02-06 00:47
浏览 33

绑定到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.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
    • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
    • ¥15 matlab有关常微分方程的问题求解决
    • ¥15 perl MISA分析p3_in脚本出错
    • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
    • ¥15 ubuntu虚拟机打包apk错误
    • ¥199 rust编程架构设计的方案 有偿
    • ¥15 回答4f系统的像差计算
    • ¥15 java如何提取出pdf里的文字?
    • ¥100 求三轴之间相互配合画圆以及直线的算法