2

フォームを作成しようとしていてremote: true、すべての設定が完了しています。送信ボタンをクリックすると、毎回エラー アクションがトリガーされます。これが私の CoffeeScript のセットアップ方法です。

$(document).ready ->
  $("#new_report").on("ajax:success", (e, data, status, xhr) ->
    $("#new_report").append "<p>SUCCESS</p>"
  ).bind "ajax:error", (e, xhr, status, error) ->
    $("#new_report").append "<p>ERROR</p>"

そして私のReports_Controller

  def create
    @report = Report.new(params[:report])

    respond_to do |format|
    if @report.save
    format.json { render json: "Created", :status => :created }
     else
    format.json { render json: @report.errors, status: :unprocessable_entity }
    end
     end

そして私のフォーム:

    <%= form_for(@report, remote: true ) do |t| %>
<p id="reportalert"></p>
    <%= t.text_field  :plant_site,    placeholder: "Plant Site" %>

    <%= t.text_field  :route_number,  placeholder: "Route Number" %>

    <%= t.text_field  :driver_name,   placeholder: "Driver name if available" %>

    <%= t.date_select :date_recorded, html: { class: "input-block-level" } %>

    <%= t.text_field  :action,        placeholder: "Action taken" %>

    <%= t.text_area   :report_body,   placeholder: "What you witnessed",
                                     style: "height: 300px;",
                                     class: "input-block-level" %>

    <%= t.submit     "File Report",  class: "btn btn-primary btn-large" %>

    <% end %>

しかし、Rails ログを確認すると、200 応答のみで、エラーはなく、情報はデータベースに送信されているのに、なぜajax:errorトリガーされるのでしょうか? ajax:errorandajax:successajaxSuccessandに置き換えてみましたajaxErrorが、何もしません。どんな情報でもありがたいです。

私は従おうとしています: http://edgeguides.rubyonrails.org/working_with_javascript_in_rails.html

4

1 に答える 1

1

コントローラーからの JSON 応答でステータスを返していないようです。これは、jQuery で ajax:success をトリガーするものです。

if ( status >= 200 && status < 300 || status === 304 ) {....}

したがって、respond_to ブロックは次のようになります。

respond_to do |format|
  if @report.save
    format.json { render json: "Created", :status => :created }
  else
    format.json { render json: @report.errors, status: :unprocessable_entity }
  end
end
于 2013-03-13T23:06:30.507 に答える