我完全不知道如何让这个请求通过ajax而不抛出406错误。我正在尝试使用 ajax 将商品添加到购物车,并且该商品确实被添加,并且刷新后购物车也会更新。我收到的所有内容都是 xhr 通知,其中包含 406 错误。非常感谢任何帮助。
产品 Controller
class ProductsController < ApplicationController
def index
@products = Shoppe::Product.root.ordered.includes(:product_categories, :variants)
@products = @products.group_by(&:product_category)
end
def show
@product = Shoppe::Product.root.find_by_permalink(params[:permalink])
end
def buy
@product = Shoppe::Product.root.find_by_permalink!(params[:permalink]) || params[:variant] ? Shoppe::Product.root.find_by_permalink!(params[:permalink]).variants.find(params[:variant].to_i) : @product
current_order.order_items.add_item(@product, 1)
respond_to do |format|
format.js
end
end
end
显示.html.erb
<h2><%= @product.name %></h2>
<% if @product.default_image %>
<%= image_tag @product.default_image.path, :width => '200px', :style => "float:right" %>
<% end %>
<p><%= @product.short_description %></p>
<p>
<% if @product.has_variants? %>
<% @product.variants.each do |v| %>
<%= form_tag product_path(@product.permalink, @product.permalink, :variant => v.id ),id: '#submit-form', remote: true do %>
<%= submit_tag 'Add to basket', :disabled => !v.in_stock? %>
<% end %>
<% end %>
<% else %>
<b><%= number_to_currency @product.price %></b>
<%= link_to "Add to basket", product_path(@product.permalink), :method => :post %>
<% end %>
</p>
<hr>
<%= simple_format @product.description %>
<hr>
<p><%= link_to "Back to list", root_path %></p>
路线.rb
Rails.application.routes.draw do
mount Shoppe::Engine => "/admin"
get "product/:permalink", to: "products#show", as: "product"
post "product/:permalink", to: "products#buy", as: "buy"
get "basket", to: "orders#show"
delete "basket", to: "orders#destroy"
root to: "products#index"
end
产品.js.erb
$(document).ready(function() {
var data = $('#submit-form').attr('action')
$.ajax({
type: 'POST',
url: data
});
});
最佳答案
查看format.js
的作用,我发现了这个:rails respond_to format.js API
看起来 buy
操作中的 format.js
将呈现 buy.js
文件。您尚未显示此文件,因此我认为它不存在。
我认为你想要做的是渲染 json,这很简单。您可以替换:
respond_to do |format|
format.js
end
这样:
render json: <your object>.to_json
请确保在发送响应之前删除所有私有(private)数据。
顺便说一句,您可能应该将回调附加到您的 $.ajax
调用中。
关于javascript - Ajax 和 Rails 完成 406 Not Acceptable ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39822541/