在rails应用程序中发送AJAX Post Jquery
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17559563/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sending AJAX Post Jquery in rails application
提问by Filip Bartuzi
With simple controller:
使用简单的控制器:
def new
@product = Product.new
respond_to do |format|
format.html #new.html.erb
format.json { render json: @product}
end
end
def create
@product = Product.new(params[:product])
respond_to do |format|
if @product.save
format.html { redirect_to @product, notice: "Save process completed!" }
format.json { render json: @product, status: :created, location: @product }
else
format.html {
flash.now[:notice]="Save proccess coudn't be completed!"
render :new
}
format.json { render json: @product.errors, status: :unprocessable_entity}
end
end
end
and simple ajax request
和简单的ajax请求
$("h1").click ->
$.post
url: "/products/"
data:
product:
name: "Filip"
description: "whatever"
dataType: "json"
success: (data) ->
alert data.id
im trying to send new product but server answers
我试图发送新产品但服务器回答
[2013-07-09 18:44:44] ERROR bad URI `/products/[object%20Object]'.
[2013-07-09 18:44:44] 错误 URI '/products/[object%20Object]'。
and nothing changes in database. Why instead of getting /products uri its taking prducts/[oobject] thing? Whats wrong there?
并且数据库中没有任何变化。为什么不是获取 /products uri 它获取 prducts/[oobject] 的东西?那里有什么问题?
回答by dasnixon
Try this out:
试试这个:
CoffeeScript
咖啡脚本
$ ->
$("h1").click ->
$.ajax({
type: "POST",
url: "/products",
data: { product: { name: "Filip", description: "whatever" } },
success:(data) ->
alert data.id
return false
error:(data) ->
return false
})
ES6-ified
ES6 化
$(() => $("h1").click(() => $.ajax({
type: "POST",
url: "/products",
data: { product: { name: "Filip", description: "whatever" } },
success(data) {
alert(data.id);
return false;
},
error(data) {
return false;
}
})));