如何在 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 %>
这是我知道的:
- 表单设置为data-remote="true" 所以表单由JS处理
- 表单作为 POST 请求提交到 /runs 路由
- 运行控制器设置为 respond_to ajax
- create.js.erb 文件 应该 自动调用,因为控制器设置为处理 JS。
这是让我有点困惑的地方:
我是否需要 .ajax 方法 如果 我有一个 create.js.erb 文件?其他 SO 问题提到设置 dataType = "script"。据我所知,我不需要这个文件。例如:
$('#run-creation-form').submit(function() {
var valuesToSubmit = JSON.stringify($(this).serialize());
console.log(valuesToSubmit);
$.ajax({
type: "POST",
url: '../runs/',
data: valuesToSubmit,
dataType: "script"
}).success(function(data) {
console.log(data);
// $('#run-breakdown').html(data);
}).error(function(error) {
console.log(error);
});
return false; // prevents normal behaviour
});
};
- 当我尝试使用上面的 js 时,当数据类型设置为脚本时,post 请求 returns 500 错误。如果我将 dataType 设置为 json,它可以正常工作,但部分仍然无法呈现。
我参考过的资源(我没有足够的声誉 post 所有链接):
- https://www.railstutorial.org/book/following_users#code-relationships_controller_ajax
- jQuery post to Rails
- Rails 指南:使用 Javascript
- 许多其他 SO posts
在 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"}
希望这对您有所帮助..
问题: 部分在 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 %>
这是我知道的:
- 表单设置为data-remote="true" 所以表单由JS处理
- 表单作为 POST 请求提交到 /runs 路由
- 运行控制器设置为 respond_to ajax
- create.js.erb 文件 应该 自动调用,因为控制器设置为处理 JS。
这是让我有点困惑的地方:
我是否需要 .ajax 方法 如果 我有一个 create.js.erb 文件?其他 SO 问题提到设置 dataType = "script"。据我所知,我不需要这个文件。例如:
$('#run-creation-form').submit(function() { var valuesToSubmit = JSON.stringify($(this).serialize()); console.log(valuesToSubmit); $.ajax({ type: "POST", url: '../runs/', data: valuesToSubmit, dataType: "script" }).success(function(data) { console.log(data); // $('#run-breakdown').html(data); }).error(function(error) { console.log(error); }); return false; // prevents normal behaviour }); };
- 当我尝试使用上面的 js 时,当数据类型设置为脚本时,post 请求 returns 500 错误。如果我将 dataType 设置为 json,它可以正常工作,但部分仍然无法呈现。
我参考过的资源(我没有足够的声誉 post 所有链接):
- https://www.railstutorial.org/book/following_users#code-relationships_controller_ajax
- jQuery post to Rails
- Rails 指南:使用 Javascript
- 许多其他 SO posts
在 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"}
希望这对您有所帮助..