我正在寻找this guide来帮助我设置一个"添加到购物车"我的应用程序中的功能。
在指南中,作者只允许用户在登录时添加到购物篮中(这也意味着按钮在此之前不可见),但我不想被此限制,所以"添加到购物车"永远是可见的,但是当你没有登录时点击,那么你将被重定向到登录/注册页面。
在控制器中,我们使用的是import numpy as np
import cv2
cascade = cv2.CascadeClassifier('data/haarcascades/haarcascade_frontalface_alt.xml')
img = cv2.imread('rectangle.png')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
rawrects = cascade.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=1, minSize=(5, 5), flags = cv2.CASCADE_SCALE_IMAGE)
# rects, weights = cv2.groupRectangles(np.array(rawrects).tolist(), 1, 0.2)
print "nrects %d" % len(rawrects)
for i, r in enumerate(rawrects):
weight = weights[i]
rectline = "%f %f %f %f %d\n" % (r[0], r[1], r[2], r[3], weight)
print rectline
p1 = (r[0], r[1])
p2 = (r[0]+r[2], r[1]+r[3])
cv2.rectangle(img, p1, p2, (0,0,255))
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
,默认情况下会在您注册/登录后重定向到您来自的网页(或者我相信,请告知这是否不正确)。< / p>
我遇到的问题是通过XHR请求实现此目的。到目前为止这是设置
before_filter :authenticate_user!
查看
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
的CoffeeScript
<%=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 %>
当我点击&#34;添加到购物车&#34;时会发生什么?是请求失败并且控制台中的$(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
我该如何处理?
答案 0 :(得分:1)
你应该在你的ajax响应中捕获401,然后像这样重定向:
$(document).on "ajaxError", (event, request, settings) ->
if request.status == 401
window.location.href = '/'