如何在 ajax POST 请求成功后呈现 rails 部分?

How to render rails partial after a successful ajax POST request?

问题: 部分在 ajax post 请求后没有更新。 Create.js.erb 不执行。我已将 console.log 消息添加到此文件,但它从未出现在控制台中。

提交表单后,我查看日志,发现 post 已成功创建:

Started POST "/runs" for 127.0.0.1 at 2017-04-11 08:57:25 -0700
  Processing by RunsController#create as JS
    Parameters: {"utf8"=>"✓", "run"=>{"skater_id"=>"2", "competition_id"=>"31", "start_time"=>"1", "stop_time"=>"2", "score"=>"5", "best_trick"=>"0"}, "commit"=>"Create Run"}
    User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 5]]
     (0.1ms)  begin transaction
    SQL (0.3ms)  INSERT INTO "runs" ("start_time", "stop_time", "skater_id", "competition_id", "score", "best_trick", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?)  [["start_time", 1], ["stop_time", 2], ["skater_id", 2], ["competition_id", 31], ["score", 5.0], ["best_trick", "f"], ["created_at", "2017-04-11 15:57:25.602458"], ["updated_at", "2017-04-11 15:57:25.602458"]]
     (2.0ms)  commit transaction
  Completed 200 OK in 5ms (Views: 0.3ms | ActiveRecord: 2.4ms)

运行的控制器

def create
  @run = Run.new(run_params)
  @runs = Run.all
  respond_to do |format|
    if @run.save
      format.json { render json: @runs }
      format.html { redirect_to :back, :notice => 'Run was successfully created.' }
    else
      format.html { render action: "new" }
      format.json { render json: @run.errors, :status => :unprocessable_entity }
    end
  end
end

create.js.erb

$("#run-breakdown").html("<%= escape_javascript(render partial: 'runs/run') %>");

/* let's check and see if this is executing */
console.log("Is this file being executed?..");

运行创作形式

<%= form_for(@run, remote: true, :html => {class:"form-horizontal", role: "form", id:"run-creation-form"}) do |x| %>
    <!-- FIELDS & STYLING REMOVED FOR BREVITY -->
    <%= x.submit class:"btn btn-primary" %>
<% end %>

这是我知道的:

这是让我有点困惑的地方:

我参考过的资源(我没有足够的声誉 post 所有链接):

在 post来到这里之前,我已经在这方面花费了大量时间。如果有人能给我指明正确的方向,我将成为一个快乐的人。感谢阅读。

您需要设置控制器以响应 JS。请记住 js != json.

def create
  @run = Run.new(run_params)
  @runs = Run.all
  respond_to do |format|
    if @run.save
      format.json { render json: @runs }
      format.html { redirect_to :back, :notice => 'Run was successfully created.' }
      format.js
    else
      format.html { render action: "new" }
      format.json { render json: @run.errors, :status => :unprocessable_entity }
      format.js { render action: "new" }
    end
  end
end

不传递块将触发 rails 默认渲染行为 create.erb.js

Do I need an .ajax method if I have a create.js.erb file?

没有。您已经在使用 the Rails UJS driver 发送 ajax 请求。否则日志中的响应类型将为 :html.

Other SO questions mention setting the dataType = "script". To the best of my knowledge, I should not need this file.

你是对的。 Rails UJS 默认使用 javascript 接受类型 header。例如,仅当您需要 JSON 响应时才需要设置数据类型。

您的控制器丢失了 format.js。 Rails 会在您发出 AJAX 请求时查找它。

respond_to do |format|
    if @run.save
     format.html { redirect_to :back, :notice => 'Run was successfully created.' }
     format.json { render json: @runs }
     format.js
    else

只需在控制器的创建方法中试试这个:

 respond_to do |format|
    if @run.save
      format.json { render json: @runs }
      format.html { redirect_to :back, :notice => 'Run was successfully created.' }
      format.js {}
    else
      format.html { render action: "new" }
      format.json { render json: @run.errors, :status => :unprocessable_entity }
   end
  end

我们需要指定要呈现的格式。你没有指定js格式。当发现 format.js 为空时 rails 检查方法名称的文件是否存在并呈现该 js。 create.js.erb 在这种情况下。您还可以将其他文件指定为:

format.js { render "some_other_jserb_file"}

希望这对您有所帮助..