无法回答ajax回应

时间:2017-01-03 14:18:50

标签: ruby-on-rails ajax

我确实有控制器动作

def create
    @place = Place.new(place_params) 

    respond_to do |format|
  if @place.save       
    format.json { render json: @place, status: :created }      
  end
end

和表格

        div.col-sm-6
        h1 Place
        =form_for Place.new, remote: true do |f|                                                                
          div
            = f.label :address, class: 'label_hidden'
            = f.text_field :address, class: "form-control"
          div
            = f.label :title, class: 'label_hidden'
            = f.text_field :title, class: "form-control"
          div 
            = f.label :longitude, class: 'label_hidden' 
            = f.text_field :longitude, class: "form-control"
          div
            = f.label :latitude, class: 'label_hidden'
            = f.text_field :latitude, class: "form-control"
          div
            = f.submit 'Create', class: "btn btn-default"

所以我需要得到一个ajax响应。我试过这样的事情

$(document).ready ->
  $("#new_place").on("ajax:success", (e, data, status, xhr) ->
      console.log xhr.responseText
    ).on "ajax:error", (e, xhr, status, error) ->
      console.log "ERROR"

但这不起作用。需要一些帮助

1 个答案:

答案 0 :(得分:1)

您需要设置表单,以便Rails ujs发送json而不是js的请求。

= form_for Place.new, data: { remote: true, type: 'json' } do |f|