【问题标题】:Rails: How can I propagate a view update from a JQuery post?Rails:如何从 JQuery 帖子传播视图更新?
【发布时间】:2014-08-31 02:33:54
【问题描述】:

我有一个 Rails 控制器 welcome_controller.rb,它定义了 indexcommit 方法。 index 方法在index.html.erb 处隐式渲染模板,该模板具有select_tagbutton_tag

select_tag 间接绑定到模型。

单击mybutton 时,我将带有JQuery 的coffeescript 设置为发送post,将参数传递给控制器​​中的commit 方法。

虽然调用了commit 方法,更新了与someselecttag 绑定的模型SomeModel,但在完成浏览器刷新之前它不会在页面中更新。如何在视图中显示someselecttag 的更新?我意识到我可以直接从 JQuery 更新someselecttag,但它并没有直接从模型本身获取数据。重写此功能的可接受的“Rails”方式是什么?

控制器welcome_controller.rb

def index
    @somelist = SomeModel.all
end

def commit
    params.each do |param|
        SomeModel.new(param)
        SomeModel.save!
    end
    render :nothing => true
end

查看模板 index.html.erb

<%= options = options_from_collection_for_select(@somelist, 'id', 'name') %>
<%= select_tag :someselecttag, options, multiple: true %>
<%= button_tag "do stuff", :id => "mybutton" %>

咖啡脚本

$ ->
    $("#mybutton").click(->
        collection_of_stuff = somefunctionthatineededtousejqueryfor()
        $.post "/welcome/commit", collection_of_stuff
    )

【问题讨论】:

    标签: jquery ruby-on-rails coffeescript refresh


    【解决方案1】:

    commit 操作应返回模型的更新副本(例如 JSON)。然后在 ajax success 上,您可以获取此模型数据并使用它更新 DOM。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-14
      相关资源
      最近更新 更多