【发布时间】:2014-07-12 09:00:29
【问题描述】:
当我尝试通过 AJAX 在 Rails 4 中更新会话时,我遇到了问题。我有一些咖啡:
ready = ->
$('#_usa-shipping_free').change (event) ->
if $('#_usa-shipping_free').prop('checked')
select_wrapper = $('#shipping-wrapper')
select_wrapper.empty
url = "/shipping_cart?shipping_type=free&remote=true"
select_wrapper.load(url)
updateTotal()
return
$('#_usa-shipping_priority').change (event) ->
if $('#_usa-shipping_priority').prop('checked')
select_wrapper = $('#shipping-wrapper')
select_wrapper.empty
url = "/shipping_cart?shipping_type=priority&remote=true"
select_wrapper.load(url)
updateTotal()
return
updateTotal = ->
$.ajax(
url: "http://localhost:3000/order/get_total",
contentType: 'text/plain'
).success (data) ->
$("#order-total").html("Total $" + data.total)
return
.fail ->
return
$(document).ready(ready)
$(document).on('page:load', ready)
和控制器动作:
def shipping_cart(shipping_type = params[:shipping_type])
if shipping_type == 'international'
session[:shipping_cost] = Order::INTERNATIONAL_SHIPPING_COST
elsif shipping_type == 'priority'
session[:shipping_cost] = Order::PRIORITY_SHIPPING_COST
else
session[:shipping_cost] = Order::FREE_SHIPPING_COST
end
if params[:remote]
render partial: 'shipping_cart'
return
end
end
此代码必须根据包含运输选项的单选按钮更新包含订单总额的字段。相反,它无论如何都不起作用。如果我删除 updateTotal() 的调用,接下来的工作是:打开页面 -> 选择收音机 -> 刷新页面 -> 重新计算总数。但我在 AJAX 中需要它。我将会话用于 TOTAL 和 SHIPPING_COST。
这是我的 GET_TOTAL 操作:
def get_total
total = 0.to_f
books = Book.all
books.each do |book|
if session[:cart].include? book.id
total = total + book.price.to_f
end
end
if session[:discount_code] != nil && session[:discount_code].blank? == false
discount_code = DiscountCode.find_by_code(session[:discount_code])
unless discount_code.nil?
unless discount_code.fixed_discount.blank?
total = total - discount_code.fixed_discount
else
total = total - (total / 100 * discount_code.discount_percents )
end
end
end
total = total + session[:shipping_cost].to_f
total = total.round(2)
session[:total] = total
output = {'total' => "#{total}"}.to_json
respond_to do |format|
format.json { render json: output, status: 200 }
format.html { total }
end
end
在每个操作之前,除了 SUBMIT(在其中我尝试使用所有此功能),我将 SHIPPING_COST 设置为 0。
当我尝试使用 puts session[:shipping_cost] 向控制台显示 shipping_cost 时,在 shipping_cart 中我得到正确的值,但在 get_total - 0 中。
有时功能有效,但它是几次之一,我点击 FREE_SHIPPING,但我的 TOTAL 加上 PRIORITY_SHIPPING。
这是我的提交操作,也许有帮助:
def submit
session[:order_id] = params[:order_id]
@order = Order.find(session[:order_id])
@order.total = get_total
books = Book.all
books.each do |book|
if session[:cart].include? book.id
@order.books << book
end
end
@order.save
@books = Book.all
@total = get_total
@shipping_types = get_types_of_shipping(@order.country)
puts @order.country
if @order.country == 'United States'
session[:shipping_type] = 'free'
else
session[:shipping_type] = 'international'
end
shipping_cart(session[:shipping_type])
puts session[:shipping_type]
puts session[:shipping_cost]
end
【问题讨论】:
-
调用 AJAX 选项时 Rails 日志显示什么?
标签: jquery ajax session ruby-on-rails-4