2014-03-29 103 views
0

我想用ajax重寫我的應用程序中的某些操作。Rails ajax:無法加載資源:服務器響應狀態爲404(未找到)

items_controller:

... 
def add_to_cart 
    @cart = Cart.where(id: session[:cart_id]).first 
    @cart = Cart.create if @cart.nil? 
    session[:cart_id] = @cart.id 
    session[:cart_items] = @cart.items 
    session[:cart_items] << @item 
    redirect_to root_url 
end 
... 

items.js:

jQuery(function($) { 
    $(".addtoCart").click(function() { 
    var current_item = $(this).parents('tr')[0]; 
    if(confirm("Add to cart")) { 
     $.ajax({ 
     url: '/items/' + $(current_item).attr('data-item-id') + '/add_to_cart', 
     type: 'POST' 
     }); 
    }; 
    }); 
}); 

視圖文件:

%tr{"data-item-id" => "#{i.id}"} 
    %td 
    %span.addtoCart Add to cart 

路線:

Store::Application.routes.draw do 

    root 'items#index' 

    resources :items 

    resources :items do 
    get :add_to_cart, on: :member 
    end 

end 

當我點擊Add to cart時,出現錯誤Failed to load resource: the server responded with a status of 404 (Not Found)POST http://localhost:3000/items/13/add_to_cart 404 (Not Found),但存在/items/13。我在哪裏犯了一個錯誤?

錯誤堆棧跟蹤:

Started POST "/items/13/add_to_cart" for 127.0.0.1 at 2014-03-30 02:55:03 +0400 

ActionController::RoutingError (No route matches [POST] "/items/13/add_to_cart") 

謝謝!

+0

您可以共享定義的'routes'。此外,分享錯誤的完整堆棧跟蹤。 –

+0

您忘記添加完整的錯誤堆棧跟蹤。 –

+0

@KirtiThorat從瀏覽器的開發工具中加入了stacktrace(不知道我是否明白你的意思) –

回答

0

如下更改路線:

root 'items#index' 

    resources :items do 
    post :add_to_cart, on: :member 
    end 

我轉換add_to_cart請求到post而不是get因爲你燒成post請求和所定義的路線爲get。 此外,我刪除了重複路線定義resources :items

相關問題