【问题标题】:Rails ajax updating the UI on successRails ajax 成功更新 UI
【发布时间】:2014-10-30 08:47:18
【问题描述】:

我有一个简单的帖子页面,用户可以在其中创建新帖子 - 表单是 ajax(我正在使用 turbolinks)。

  • ajax 成功后更新 UI 的 Rails 方式是什么?

我认为这是我的选择:

  1. 在 ajax:success 触发时使用 javascript 重新加载页面

  2. 在 Rails 控制器中,以 json 格式返回新帖子。然后在 ajax:success 我需要以某种方式创建一个模板

例如:

$("<div id='new-post'>").html(ajaxResult)
code to append the div to my posts
  • 这是或多或少的方法吗? (我不会在这里使用 ember 或 angular)
  • 有什么理由更喜欢第一个或第二个选项?

【问题讨论】:

  • 选项2,通过rails更新
  • 人们会使用 handlebars.js 来处理类似的事情,还是仅当它是一个非常复杂的 UI 时才使用?
  • 对你来说,车把有点矫枉过正:)

标签: ruby-on-rails ajax


【解决方案1】:

您可以选择选项 2 发送新的 js 并使用 rails 将其添加到 div 模板中

例如:

_form.html.erb

 <%= form_for(@model), :html => {remote: true} do |f| %>
        your input fields code here

 <% end %>

控制器。

   def create
    respond_to do |format|
     if @model.save
        format.js
     else
         render 'new'
     end
     end

create.js.erb

$("#get_input").html(<%= j ({render :partial => "create"})%>) **#get_input is your div id**

_create.html.erb

#write your template code here

【讨论】:

  • 啊,我喜欢我可以用这种方式使用我的部分,如果我理解正确的话,我不需要在我的 javascript 中构建 html
  • @Joel_Blum 要显示来自 ajax 的部分数据,您需要将其附加到某些 html 元素。
  • 是的,剩下的就是将附加代码添加到 create.js.erb 。如果您不需要任何花哨的东西,我认为这是一个合理的解决方案
【解决方案2】:

有很多方法可以做到:)

例如。你可以发送不是 json 而是 js 请求

def some_action
  respond_to do |format|
    format.html
    format.js
  end
end

然后在您的 /views/../some_action.js.erb 中

$("<div id='new-post'>").html("<%=j({render here what you want}>")

或者你真的可以处理 json。然后你需要使用像https://github.com/netzpirat/haml_coffee_assets模板系统这样的smth,并根据你的JSON轻松创建js模板

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-28
    • 2012-12-29
    • 1970-01-01
    相关资源
    最近更新 更多