【问题标题】:Rails 4 + jQuery: PUT ajax requestRails 4 + jQuery:PUT ajax 请求
【发布时间】:2016-10-19 15:13:06
【问题描述】:

Ajax 请求对我来说仍然很新,但我有一个带有按钮的食谱索引,可让您收藏食谱。

<i class="favorite" data-recipe="<%= recipe.id %>">

...我正在尝试对路由使用 PUT 请求:

favorite_recipe PUT    /recipes/:id/favorite(.:format)    recipes#favorite

... 使用以下 jQuery 函数:

    $(".favorite").click(function(){
        $(this).toggleClass("favorited");
        var recipe_id = $(this).data("recipe");

        // displays properly when I console.log() it
        var url_path = '/recipes/' + recipe_id + '/favorite'


        $.ajax({
            url: url_path,
            type: 'PUT'
        })
    })

但在我的开发者控制台中,我收到 404 错误,并且显示的 url 是 Request URL:http://localhost:3000/recipes 而不是 http://localhost:3000/recipes/:recipe_id/favorite

我做错了什么?我需要使用 data 参数来提供 id 吗?

【问题讨论】:

  • 正如 gil.neo 所说,请确保您拥有 routes.rb 以及通往此收藏夹的路线。此外,我相信您需要在您的食谱控制器中使用类似以下内容的方法:正如 gil.neo 所说,确保您的 routes.rb 具有指向此收藏夹的路由。此外,我相信您需要在食谱控制器中使用类似以下内容的方法:` def favorite @recipe = Recipe.find(params[:id]) @Recipe.increment!(:favourite) end `

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


【解决方案1】:

好的,我正在更改答案,因为我注意到您确实有该请求的路线。

我相信您收到此错误是因为您没有在控制器中正确处理请求。尝试将以下内容添加到您的控制器中,以使其处理 JSON 请求。

respond_to do |format|
      format.json do
        render :json => {success: 'yes'}
      end
end

【讨论】:

    【解决方案2】:

    试试这个。

    $(".favorite").click(function(){
        $(this).toggleClass("favorited");
        var recipe_id = $(this).data("recipe");
    
        // displays properly when I console.log() it
        var url_path = "<%= favorite_recipe_path %>"
    
    
        $.ajax({
            url: url_path,
            type: 'PUT',
            data : JSON.stringify({id: recipe_id}),
            dataType: "json",
        })
    })
    

    【讨论】:

    • @Jeremy Thomas,试试这个/
    • @Jeremy Thoas,你实现了吗?
    • ajax 应该使用方法而不是类型?
    • 没有 ajax 调用具有 HTTP 方法的 type 属性。
    • 不走运,在我看到http://localhost:3000/recipes 的请求的开发人员工具中可能值得注意,但在“发起者”下它显示http://localhost:3000/recipes/:recipe_id/favorite。此外,您的 rails url helper 不起作用,因为它需要一个 ID,我无法将 JS 变量传递给 rails url helper
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-15
    • 2013-07-08
    • 1970-01-01
    相关资源
    最近更新 更多