在Ruby on Rails 4上的AJAX请求上读取js.erb上的Controller变量

时间:2015-05-21 16:30:42

标签: jquery ruby-on-rails ruby ajax

我在从AJAX请求做出响应时遇到问题。我想要做的是使用js.erb文件上的控制器变量。

我将逻辑简化为

testcontroller.rb

def test
  @test = "some value"
  respond_to do |format|
    format.js 
  end
end

new.html.erb

<%= button_tag "test button", type: 'button', id: 'testbutton' %>
$("#testbutton").on("click", function() {
  $.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  url: "/ajax/test",
  dataType: "script",
  });
});

的routes.rb

post 'ajax/test' => 'testcontroller#test'

test.js.erb

alert("<%= @test %>");

我收到一个空警报

enter image description here

我哪里出错?

编辑 - 已解决

'test'方法在下面(但不在里面,我仔细检查)控制器类的私有方法。当我把它放在上面时,它工作正常。

无论如何,谢谢大家的时间。

1 个答案:

答案 0 :(得分:0)

我认为您展示的代码是正确的。您可能需要重新启动服务器,否则可能会有一些重复。你有多个TestController吗?

此外,post 'ajax/test' => 'testcontroller#test'应为post 'ajax/test' => 'test_controller#test',应将其命名为TestController

此外,注入JS的更好方法是使用alert("<%= j @test.html_safe %>");