gpt4 book ai didi

javascript - ajax 调用不更新 Rails 上的内容

转载 作者:行者123 更新时间:2023-11-28 06:16:05 25 4
gpt4 key购买 nike

我试图在我的应用程序中实现一点 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>

销毁.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

关于javascript - ajax 调用不更新 Rails 上的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35955098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com