programing

레일 응용 프로그램에서 AJAX Post Jquery 전송

jooyons 2023. 8. 18. 22:30
반응형

레일 응용 프로그램에서 AJAX Post 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

그리고 간단한 아약스 요청.

$("h1").click ->
  $.post
    url: "/products/"
    data:
        product:
            name: "Filip"
            description: "whatever"

    dataType: "json"
    success: (data) ->
      alert data.id

새로운 제품을 보내려고 하는데 서버가 답을 합니다.

[2013-07-09 18:44:44] ERROR bad URI '/products/[object%20Object]'.

데이터베이스에 변경 사항이 없습니다.왜 /productsuri를 받는 대신 제품/[object]을 가져가는 것입니까?뭐가 잘못됐어요?

사용해 보십시오.

커피스크립트

$ ->
  $("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;
  }
})));

언급URL : https://stackoverflow.com/questions/17559563/sending-ajax-post-jquery-in-rails-application

반응형