使用 jquery 和 Rails 加载部分内容
我很好奇用 jquery 加载 Rails 部分的最佳方法是什么。到目前为止,我已经尝试了一个不起作用的解决方案:
$('#imagecontent').load('/newsletters/_image_gallery.html.erb', function() {
alert('Load was performed.');
});
为此构建单独的操作和/或控制器并设置路线的最佳解决方案是?我这么问是因为让第一个解决方案工作似乎更容易,也许不那么轻松。
谢谢。
Im curious about what the best way to load a rails partial with jquery. So far I have tried a solution not working:
$('#imagecontent').load('/newsletters/_image_gallery.html.erb', function() {
alert('Load was performed.');
});
Is the best solution to build a seperate action and/or controller for this and set up a route? Im asking because making the first solution work seems more easy, perhaps not so restful.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您不应该能够从 HTTP 请求访问模板文件 (.erb),这是非常糟糕的做法。我建议您将它们放在 Web 服务器路径之外,并且仅通过您的应用程序访问它们。
我不确定 Rails,但我想您需要创建一个单独的控制器(或其他)来执行此操作。
编辑这是因为 .erb 文件是嵌入式 Ruby 文件,如果您尝试请求它们,您将获得所有不需要的数据,例如
<%= page_title %>
,您不想向用户展示。因此,您需要通过 Rails 应用程序传递这些 .erb 文件,以便将它们正确解释为 HTML。You should not be able to access Template files (.erb) from HTTP requests, this is very bad practice. I suggest you put them outside your web servers path and access them only through your application.
I'm not sure about Rails, but I suppose you need to create a separate controller (or whatever) to do this.
EDIT this is because .erb files are Embedded Ruby files, and if you try to request them you will get all unwanted data, like
<%= page_title %>
, that you don't want to show the users. Therefore you need to pass these .erb files through your Rails application so that they are properly interpreted into HTML.代码不起作用的原因是 Rails 不会向外部公开视图文件。为了实现你想要的东西,你需要一个动作来渲染这个部分:
还有一个名为 jRails 的插件,它用等效的面向 jquery 的辅助程序替换标准 ajax 辅助程序(使用原型)。在你的情况下,你会使用类似的东西
,甚至更多,在 Rails 3 中你将不需要它。请参阅此链接。
The reason that code doesn't work is that rails doesn't expose view files outside. To achieve the thing you want, you'll need an action which would render this partial:
Also there is a plugin called jRails which replaces standard ajax helpers (which use prototype) with equivalent jquery-oriented ones. In your case you would use something like
And even more, in Rails 3 you won't need it. See this link.
这就是您想要的:
http://www.slideshare.net/JamesEdwardGrayII /ajax-with-jquery-in-rails
Here's what you want:
http://www.slideshare.net/JamesEdwardGrayII/ajax-with-jquery-in-rails
另一种选择:
Another alternative:
使用 Rails 3 你可以做...
控制器
视图 - haml.erb(html.erb) 或 js.erb
如果 Rails 2 (只有原型可用,除非添加 noConflict) 你可以尝试这个...
在控制器中
调用你的 js
你的函数...
我确实同意中微子的观点,即这可以通过动作更好地处理。
希望这有帮助
With rails 3 you could do...
controller
view - either haml.erb(html.erb) or js.erb
You could try this if rails 2 (only prototype available unless noConflict added)...
In the controller
Call your js
Your function...
I do agree with neutrino that this could be better handled via an action.
Hope this helps