【问题标题】:jQuery GET Rails controller methodjQuery GET Rails 控制器方法
【发布时间】:2013-12-18 04:06:34
【问题描述】:

jQuery .get() 如何与 Rails 方法一起工作?我在documents 控制器中设置了一个名为templates 的方法,我想从单独的JS 文件中的JS 方法访问该方法。通过一些研究,我发现使用.get() 是访问Rails 方法的最佳方式,但是当我这样做时,例如var templates = $.get("/documents#templates", function (data) { console.log(data) },它只是控制台记录整个/documents HTML DOM 结构。

如果你愿意,我猜我需要“劫持”路由,但我尝试添加自定义路由,控制台日志仍然返回 HTML 页面,甚至没有到达我的 Rails 控制器。

如果有帮助(尽管我对此表示怀疑,因为完全删除它不会改变控制台日志结果),这是我在控制器中的 templates 方法:

def templates
  @templates = DocumentTemplate.all
  @output = []
  @templates.each do |template|
    @output = template.content
  end
  respond_with(@output)
end

【问题讨论】:

  • 刚刚发现您需要为 $.get 的第一个参数指定一个 URL,例如“documents/templates”,而不是 Rails 控制器映射(“documents#templates”)。要查找 URL,请在控制台中运行 rake routes 或在 routes.rb 中明确指定路径(例如 get 'documents/templates', to: 'documents#templates')。
  • 谢谢!在routes.rb 中声明路径加上@Oli 下面的方法效果很好。

标签: jquery ruby-on-rails ruby-on-rails-3 get rails-routing


【解决方案1】:

如果你想用 HTML 的 sn-ps 响应 jQuery 的 GET 请求,你可以考虑渲染一个 partial layout(它不包括完整的应用程序布局)。在您的控制器中,响应可能如下所示:

def templates
  @templates = DocumentTemplate.all

  if request.xhr?
    render :partial => 'templates', locals: {:templates => @templates}
  else
    # respond with your normal layout if required
  end
end

然后在您的app/views/documents/ 文件夹中创建一个名为_templates.html.haml(或.erb)的部分文件。请注意部分名称中的前导下划线。

您将可以访问 templates 局部变量以在您的部分文件中循环(此处的语法适用于 HAML):

- templates.each do |template|
   # do what's required to present each template instance here

那么您的 jQuery GET 请求应该只收到 HTML 的部分 sn-ps:

$.get("/documents/templates", function(data) {
  console.log('data');
  alert("Load was performed.");
});

【讨论】:

  • 很抱歉我的回复延迟,但非常感谢您的解释。您的解释是有道理的,但我在控制台中收到 404 错误,因为它找不到 /documents/templates。我需要修改我的路线,不是吗?
【解决方案2】:

您到底想返回什么?有几种不同的方法,具体取决于您的需要。

$(data).find('selector') 是最不优雅的方式。您可以使用 jQuery 从完整响应中提取您需要的内容。

respond_with(@output, :layout => !request.xhr? ) 将呈现没有周围 application.html 文件的页面。以下是为 jQuery 呈现不同部分的方法。

respond_with(@output) do |format|
  format.html { render partial: 'templates' if request.xhr? }
end

如果你需要的话,你也可以很容易地发回 JSON。这里有一篇关于 Rails AJAX 各种方法的不错的博文:http://madebydna.com/all/code/2011/12/05/ajax-in-rails-3.html

【讨论】:

  • 问题是完整的响应不是它应该的。响应应该返回每个 template 实例的 content 值。但是.get() 甚至没有达到 Rails 方法……这才是真正的问题。
猜你喜欢
  • 1970-01-01
  • 2014-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多