Ajax和Rails完成406不可接受

Ajax and Rails Completed 406 Not Acceptable

本文关键字:不可接受 完成 Rails Ajax      更新时间:2023-09-26

我完全失去了如何使这个请求通过ajax而不抛出一个406错误。我试图添加一个项目与ajax购物车,项目确实得到添加和刷新后,购物车更新。我只收到一个带有406错误的xhr通知。如有任何帮助,不胜感激。

产品控制器
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

Show.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>  

routes.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

products.js.erb

$(document).ready(function() {
 var data = $('#submit-form').attr('action')
    $.ajax({
        type: 'POST',
        url: data
    });
});

查找format.js做什么,我发现这:rails respond_to format.js API

似乎format.js在您的buy行动将呈现buy.js文件。你还没有显示这个文件,所以我认为它不存在。

我在想你要做的是渲染json,这很简单。你可以替换:

respond_to do |format|
  format.js
end
与这个:

render json: <your object>.to_json

确保在发送响应之前剥离任何私有数据。

顺便说一下,你可能应该给你的$.ajax调用附加一个回调。