从Javascript调用Rails控制器操作不显示

时间:2014-11-15 12:59:53

标签: javascript jquery ruby-on-rails ajax

我正在尝试从javascript调用控制器动作。

chrome调试器显示正在进入ok的javascript(因此可以触发js click事件)。

如果我使用HTML按钮调用控制器动作,即/ home / benefits / page渲染正常(因此控制器动作代码本身可用),控制器动作就有效。

当我尝试通过javascript调用它时它似乎不起作用 - development.log似乎显示它已呈现页面,但我的网站页面没有更改为/ home / benefits / page

我在操作系统上阅读了很多教程和相关问题,但我很难过。任何帮助都将从这个令人敬畏的SO社区中受到赞赏! ; - )

控制器代码:

  def set_analysis_input
     redirect_to home_benefits_path
  end    

routes.rb中:

  get "trades/set_analysis_input"

HTML.ERB :(使用html按钮的第一行是好的,通过JS的第二行不起作用)

<%= link_to "Button to Call Action", trades_set_analysis_input_path, class: "btn btn-small btn-success" %>
<button id="button_to_call_controller_action">hello</button>

JS在HTML.ERB文件的末尾:

      console.log(“输入JS”);

  $(document).on('click', '#button_to_call_controller_action', function() {
    url_string = "/trades/set_analysis_input";
    $.ajax({
       url:   url_string,
       type:  'get'
    });  
  }); 

结束发展。漫画文件:

Started GET "/trades/set_analysis_input" for 127.0.0.1 at 2014-11-15 12:47:44 +0000
Processing by TradesController#set_analysis_input as */*
  User Load (0.0ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 38 ORDER BY "users"."id" ASC LIMIT 1
Redirected to http://localhost:3000/home/benefits
Completed 302 Found in 3ms (ActiveRecord: 0.0ms)


Started GET "/home/benefits" for 127.0.0.1 at 2014-11-15 12:47:44 +0000
Processing by HomeController#benefits as */*
  Rendered home/benefits.html.erb within layouts/application (0.0ms)
  User Load (0.0ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 38 ORDER BY "users"."id" ASC LIMIT 1
  Rendered layouts/_header.html.erb (0.0ms)
Completed 200 OK in 79ms (Views: 79.4ms | ActiveRecord: 0.0ms)

1 个答案:

答案 0 :(得分:0)

欢迎使用StackOverflow。问题是您正在调用控制器操作,其中包含redirect_to,这是

Completed 302 Found in 3ms (ActiveRecord: 0.0ms)

来自。如果ajax调用获得302,那么你将遇到这个问题。