Ajax 调用不更新 Rails 上的内容

ajax call not updating content on rails

本文关键字:Rails 调用 更新 Ajax      更新时间:2023-09-26

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

我将 Ajax 添加到我的销毁方法

  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>

销毁.js.erb

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

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

尝试在方法本身中呈现 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