2013-07-09 74 views
18

凭借简单的控制器:在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]的东西?那里有什么错?

+1

只是一个侧面说明,但做的respond_to |格式|对于Rails 3是不必要的。您可以在控制器的顶部使用respond_to:html,:xml,然后在action中使用@object_name。如果您有兴趣,请参阅Railscast:http://railscasts.com/episodes/224-controllers-in-rails-3?view=asciicast –

回答

29

尝试了这一点:

$ -> 
    $("h1").click -> 
    $.ajax({ 
     type: "POST", 
     url: "/products", 
     data: { product: { name: "Filip", description: "whatever" } }, 
     success:(data) -> 
     alert data.id 
     return false 
     error:(data) -> 
     return false 
    }) 
+0

为什么您返回false并且...为什么它会改变任何内容?它的工作,但仍然没有得到它的原因。 –

+2

可能是一些很好的解释这里http://stackoverflow.com/questions/855360/when-and-why-to-return-false-in-javascript – dasnixon

+0

谢谢!我发现它很有用。大! –

相关问题