首页 文章

Rails ajax:无法加载资源:服务器响应状态为404(未找到)

提问于
浏览
0

我正在尝试使用ajax在我的应用程序中重写一些操作 .

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")

谢谢!

1 回答

  • 0

    更改您的路线如下:

    root 'items#index'
    
      resources :items do
        post :add_to_cart, on: :member
      end
    

    我将 add_to_cart 请求转换为 post 而不是 get ,因为您正在触发 post 请求并将路由定义为 get . 另外,我删除了定义 resources :items 和的重复路由

相关问题