2016-10-02 63 views
0

我完全失去了如何使這個請求通過ajax而不丟回406錯誤。我試圖用ajax添加一個項目到一個購物車,並且該項目確實被添加,刷新後購物車被更新。所有我作爲xhr通知收到406錯誤。任何幫助,高度讚賞。Ajax和Rails完成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 
    }); 
}); 
+0

這有一點點猜測,因爲我現在沒有時間詳細研究它,但是在ProductsController的頂部添加'respond_to:json'解決了您的問題?如果是這樣,我會在幾個小時內發佈更詳細的答案... –

+0

@TomLord:不幸的是,它不,我不斷收到相同的406錯誤,當試圖呈現應用程序/控制器/ products_controller時軌道日誌ActionController :: UnknownFormat .rb:15:在'buy'中。 – RickD

+0

嘗試添加'dataType:'script''到你的ajax調用 –

回答

1

展望了一下format.js呢,我發現這一點:rails respond_to format.js API

看來format.jsbuy行動將呈現buy.js文件。你沒有顯示這個文件,所以我認爲它不存在。

我想知道你想要做的是呈現json,這很簡單。您可以取代:

與此:

render json: <your object>.to_json 

確保發送響應之前,剝去任何私人數據。

順便說一句,您應該附上回撥到您的$.ajax呼叫。