Rails 4 + jQuery: PUT ajax request
Rails 4 + jQuery: PUT ajax request
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吗?
好的,我正在改变我的答案,因为我注意到你有一个路由的请求。
我相信你得到这个错误是因为你没有在控制器中正确处理请求。试着在你的控制器中添加以下代码,让它处理JSON请求。
respond_to do |format|
format.json do
render :json => {success: 'yes'}
end
end
试一次
$(".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",
})
})
相关文章:
- 将对Ajax PUT的json响应重定向到要由EL解析的JSP中
- Ruby on rails-更新ajax的PUT方法
- 使用get/put/delete方法从ajax请求调用laravel-controler
- 如何在页面卸载时发送AJAX PUT请求而不取消
- UIWebView 中 PUT 或 POST 类型的 ajax 不传递 HTTP 正文
- 使用 PUT 动词调用 $.ajax 的奇怪行为
- 如何在没有AJAX的情况下将数据提交到CouchDB(使用普通形式的PUT)
- AWS S3 ajax PUT 返回“我们计算的请求签名与您提供的签名不匹配”
- jQuery AJAX PUT有空的QUERY_STRING和REQUEST PHP变量
- Backbone.js保存模型don't在android 2.x上引起ajax PUT请求
- 在knockout中ajax put或post期间自动映射ajax数据
- 使用casperjs通过AJAX发送POST/PUT
- Rails 4 + jQuery: PUT ajax request
- AJAX api PUT request
- jQuery Ajax PUT not firing
- Ajax在MVC模式下GET/POST/PUT/DELETE的区别
- jQuery AJAX PUT请求数据提交不工作
- 为什么我的AJAX请求在开发中是PUT请求,但在运行测试时是GET请求?
- 更新数据库的Ajax PUT REST请求
- 让一个按钮使用jQuery发送AJAX put请求