【问题标题】:ajax call not updating content on railsajax 调用不更新 Rails 上的内容
【发布时间】:2016-06-27 13:50:08
【问题描述】:

我试图在我的应用程序中实现一点 Ajax 似乎可以正常工作,但它不会在执行操作后更新页面。

我将 Ajax 添加到我的 Destroy 方法中

  def destroy
    @item = Item.find(params[:id])
    @item.user = current_user
    if @item.destroy
      flash[:notice] = "Item Completed"
    else
      flash[:alert] = "Item was unable to be marked completed "
    end

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

我已经用remote: true 更新了我的 _item.html.erb 和 _form.html.erb 部分

<%= content_tag :div, class: 'media', id: "item-#{item.id}" do %>
<div class="media">
  <div class="media-body">
    <small>
      <%= item.name.titleize %>
      | submitted <%= time_ago_in_words(item.created_at) %>
      <% if current_user == @user %>
      <%= link_to "Completed ", [@user, item], method: :delete,remote: true, class: 'glyphicon glyphicon-ok' %><br>
      <% end %>
    </small>
  </div>
</div>
<% end %> 

_from.html.erb

<%= form_for [@user, item ], remote: true do |f|%>
  <div class="form-group">
    <%= f.label :name, class: 'sr-only' %>
    <%= f.text_field :name , class: 'form-control', placeholder: "Enter a new item " %>
  </div>
  <%= f.submit "Submit Item", class: 'btn btn-primary pull-right' %>
<% end %>


User#show view <div class='new_item'>
<%= render :partial => 'items/form', :locals =>{:item => Item.new} %>
</div>
<% end %>
<div class='js-items'>
<% @user.items.order('created_at DESC').each do |item| %>
<%= render :partial => 'items/item' , :locals => {:item => item } %>
</div>

destroy.js.erb

$('#item-<%= @item.id %>').hide();

就像我之前说的,当我单击删除按钮时,该项目被删除,但我需要刷新页面才能看到更新的页面。任何我可能做错的想法,任何朝着正确方向的推动都将不胜感激!

【问题讨论】:

  • 是否需要刷新页面?还是只需要通过 ajax 重新加载页面内容?

标签: javascript jquery html ruby-on-rails ajax


【解决方案1】:

尝试在方法本身中渲染java脚本并检查,

def destroy
    @item = Item.find(params[:id])
    @item.user = current_user
    if @item.destroy
      flash[:notice] = "Item Completed"
    else
      flash[:alert] = "Item was unable to be marked completed "
    end

    respond_to do |format|
      format.html
      format.js { render             
          $('#item-<%= @item.id %>').hide();
        }
    end
  end

【讨论】:

    猜你喜欢
    • 2023-03-19
    • 1970-01-01
    • 2015-01-18
    • 2012-04-22
    • 2018-08-27
    • 2019-12-24
    • 2018-01-28
    • 2014-12-30
    • 1970-01-01
    相关资源
    最近更新 更多