18

使用简单的控制器:

  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]'。

并且数据库中没有任何变化。为什么不获取 /products uri 而不是获取产品 /[oobject] 的东西?那里有什么问题?

4

1 回答 1

34

试试这个:

咖啡脚本

$ ->
  $("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 化

$(() => $("h1").click(() => $.ajax({
  type: "POST",
  url: "/products",
  data: { product: { name: "Filip", description: "whatever" } },
  success(data) {
    alert(data.id);
    return false;
  },
  error(data) {
    return false;
  }
})));
于 2013-07-09T22:56:47.487 回答