javascript - Rails 4 + jQuery : PUT ajax request

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

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 吗?

最佳答案

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

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

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

关于javascript - Rails 4 + jQuery : PUT ajax request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40135405/

相关文章:

mysql - 无法获得适用于 has_many 的动态条件 :through (+ ownership)

javascript - 用大括号分割字符串成为参数

javascript - 黑色文本 - 黑色背景时为白色

jquery - 作为一个 jquery 新手,我不知何故缺少一个简单的 jquery 代码

javascript - jQuery每次循环问题

javascript - turbolinks 中的历史记录错误链接到带有哈希的页面

javascript - JQuery 跨域 GET 请求不起作用

javascript - 如何将多条线添加到 D3JS 折线图中,其中因变量数据源从范围内的不同位置开始?

javascript - jQuery 就地编辑器使用 jQuery 自动完成输入字段

css - 防止 Assets /样式表加载到 heroku 应用程序中