我正在看this guide帮助我在我的应用程序中设置“添加到购物车”功能。
在指南中,作者仅允许用户在登录后添加到购物篮(这也意味着该按钮在此之前不可见),但是我不想受此限制,因此“添加到购物车”始终可见,但如果您未登录,则单击时您将被重定向到登录/注册页面。
在 Controller 中,我们使用 before_filter :authenticate_user!
,默认情况下,一旦您注册/登录,它将重定向回您来自的页面(或者我相信,请告知如果这是不正确的)。
我遇到的问题是通过 XHR 请求来实现此目的。这是到目前为止的设置
class CartsController < ApplicationController
before_action :authenticate_user!
def show
cart_ids = $redis.smembers current_user_cart
@cart_images = Image.find(cart_ids)
end
def add
$redis.sadd current_user_cart, params[:image_id]
render json: current_user.cart_count, status: 200
end
def remove
$redis.srem current_user_cart, params[:image_id]
render json: current_user.cart_count, status: 200
end
private
def current_user_cart
"cart#{current_user.id}"
end
end
查看
<%=link_to "", data: { target: @cart_action, addUrl: add_to_cart_path(@image), removeUrl: remove_from_cart_path(@image) } do %>
<i class="di-shopping-cart-up"></i>
<span><%= @cart_action %></span> Cart
<% end %>
CoffeeScript
$(window).load ->
$('a[data-target]').click (e) ->
e.preventDefault()
$this = $(this)
if $this.data('target') == 'Add to'
url = $this.data('addurl')
new_target = "Remove from"
else
url = $this.data('removeurl')
new_target = "Add to"
$.ajax url: url, type: 'put', success: (data) ->
$('.badge-number').html(data)
$this.find('span').html(new_target)
$this.data('target', new_target)
当我点击“添加到购物车”时,请求失败,控制台中显示 401 Unauthorized
,并显示响应 您需要先登录或注册继续。
我该如何解决这个问题?
最佳答案
您应该在 ajax 响应中捕获 401,然后像这样重定向:
$(document).on "ajaxError", (event, request, settings) ->
if request.status == 401
window.location.href = '/'
关于javascript - 验证用户身份,使用 XHR 请求重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34434163/