繁体   English   中英

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

[英]Rails ajax: Failed to load resource: the server responded with a status of 404 (Not Found)

我正在尝试使用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")

谢谢!

如下更改路线:

  root 'items#index'

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM