Rails 3中使用link_to进行ajax回调的正确方法是什么?

3
这里是情景。
概要: 我有一个解决方案,但我想知道是否这是Rails 3中获得AJAX回调最好的方法。
问题: 我有一个链接,当单击它时,应该使用AJAX来更新页面上现有的HTML元素(在我的情况下是div): <div id="project_content">Change Goes here</div> 我的解决方案: 在我的projects/show.html.erb中:
true} %>
我的TasksController如下:
class TasksController < ApplicationController
    def index
        respond_to do |format|
              format.html
              format.js { render action: "index", script: true }
        end
    end
end

在我的tasks/index.js.erb文件中,我有以下内容:

$("#project_content").html("<%= escape_javascript(render :partial => 'tasks')%>");

问题:这一切都有效。但是我为什么要这样做呢?难道没有解决方案可以让我们简单地执行以下操作吗?

<%= link_to "tasks", project_tasks_path(@project), {:remote=>true, :update=>"project_content"} %>

然后将tasks/index.js.erb加载到键:update所引用的任何元素中?

1个回答

0

您正在尝试重新发明来自旧版Rails 2.3的link_to_remote。这样的解决方案通常会变得过于复杂和僵化。


我不明白您在说什么? - haroldcampbell
@haroldcampbell 花点时间研究一下 link_to_remote 的功能。它甚至有你提出的 :update 选项。 - Nash Bridges
但是 link_to_remote 已经从 Rails 3+ 中删除:话虽如此,问题仍然存在。有没有替代 link_to_remote 的方法,可以简单地提供一个 :update 哈希? - haroldcampbell
1
@haroldcampbell,你的问题是“为什么我要做这些?”答案是因为不显眼的JavaScript是正确的做事方式。这就是为什么在Rails 3中link_to_remote已经被移除的原因。 - Nash Bridges

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接