普通网友 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 如何让企业微信机器人实现消息汇总整合
    • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
    • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
    • ¥15 TLE9879QXA40 电机驱动
    • ¥20 对于工程问题的非线性数学模型进行线性化
    • ¥15 Mirare PLUS 进行密钥认证?(详解)
    • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
    • ¥20 想用ollama做一个自己的AI数据库
    • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
    • ¥15 请问怎么才能复现这样的图呀