Ajax和Rails完成406不可接受

时间:2016-10-02 22:51:16

标签: javascript jquery ruby-on-rails ruby ajax

我完全迷失了如何使这个请求通过ajax而不会丢弃406错误。我正在尝试使用ajax将项目添加到购物车,并且项目确实已添加,刷新后购物车会更新。我收到的所有内容都是xhr通知,其中包含406错误。任何帮助都非常感谢。

产品控制器

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
    });
});

1 个答案:

答案 0 :(得分:1)

查看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来电。