gpt4 book ai didi

javascript - 使用respond_to 做 |format| format.js 在模态中收藏照片后在模态中显示消息?

转载 作者:行者123 更新时间:2023-12-03 06:26:34 26 4
gpt4 key购买 nike

网络用户打开了一个显示图片的模式,他们单击:

照片/show.html.erb

<%= link_to favorite_photo_path("#{photo.id}"), method: :put do %>
<span class="glyphicon glyphicon-heart"></span>
<% end %>

最终目标是让用户保持在模式内,并在模式内显示一条消息,“您已成功收藏这张照片”...我正在我调用的 Controller 中间测试这一点respond_to do... 但是,当单击字形图标时,模型会更新,但浏览器最终卡在 www.examples.com/photos/1/favorite

路线

resources :photos do
match :favorite, on: :member, via: [:put, :delete]
end

照片 Controller

def favorite
@photo = Photo.find params[:id]
if request.put?
response = current_user.favorite_photos.new(photo: @photo)
if !response.valid?
redirect_to :back, notice: response.errors.full_messages
else
response.save
respond_to do |format|
format.js
end
end
else request.delete?
current_user.favorites.delete(@photo)
redirect_to :back, notice: 'You successfully unfavorited this photo'
end
end

照片/favorite.js.erb

 $('.modal-dialog.photo>.message').html('You have successfully favorited this photo');

当使用 html {redirect_to :back } 时,它会关闭模式。

最佳答案

要利用 JavaScript 响应,您需要将 remote: true 选项添加到链接中。

http://guides.rubyonrails.org/working_with_javascript_in_rails.html

如果您想通过 AJAX 处理此问题,请不要使用重定向返回。

还可以使用 flash.now 进行 AJAX。

而是在 JavaScript 文件中处理这两种情况。

# app/views/photos/favorite.js.erb     
<% if flash.now[:notice] %>
$('.modal-dialog.photo>.message').html("<%= j flash.now[:notice] %>")
<% else %>
$('.modal-dialog.photo>.message').html("<%= j flash.now[:alert] %>")
<% end %>

# app/views/photo/unfavorite.js.erb
<% if flash.now[:notice] %>
$('.modal-dialog.photo>.message').html("<%= j flash.now[:notice] %>")
<% end %>

这有点像notice就像成功,而alert是错误。

并将您的 Controller 更改为:

def favorite
@photo = Photo.find params[:id]
favorite_photo = current_user.favorites.build(photo: @photo)

if favorite_photo.save
flash.now[:notice] = 'You successfully favorited this photo'
else
flash.now[:alert] = favorite_photo.errors.full_messages
end
respond_to :js
end

def unfavorite
@photo = Photo.find params[:id]
current_user.favorites.delete(@photo)
flash.now[:notice] = 'You successfully unfavorited this photo'
respond_to :js
end

以及与此配置相匹配的路由。

由于各自的数据库影响,我会POST到收藏夹,DELETE到不收藏夹。

目前,您只能将 noticealert 传递给 renderredirect_to。但您可以定义自己的闪存类型。但不要限制自己只使用这两个。

if success
flash[:success] = "Something good"
else
flash[:error] = "Something bad"
end

关于javascript - 使用respond_to 做 |format| format.js 在模态中收藏照片后在模态中显示消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38624907/

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