凭借简单的控制器:在Rails应用程序发送Ajax后的Jquery
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
和简单的Ajax请求
$("h1").click ->
$.post
url: "/products/"
data:
product:
name: "Filip"
description: "whatever"
dataType: "json"
success: (data) ->
alert data.id
我尝试发送新产品,但服务器响应
[2013- 07-09 18:44:44]错误错误的URI`/ products/[object%20Object]'。
而且数据库中没有任何变化。为什么没有获得/产品uri其产品/ [oobject]的东西?那里有什么错?
只是一个侧面说明,但做的respond_to |格式|对于Rails 3是不必要的。您可以在控制器的顶部使用respond_to:html,:xml,然后在action中使用@object_name。如果您有兴趣,请参阅Railscast:http://railscasts.com/episodes/224-controllers-in-rails-3?view=asciicast –