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/