问题:部分不会在ajax发布请求后更新。 Create.js.erb不执行。我已将一个console.log消息添加到此文件,并且它永远不会出现在控制台中。如何在成功的ajax POST请求之后渲染rails partial?
提交表格后,我看日志,看看帖子已成功创建:
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 %>
这是我知道的:
- 的方式被设定为数据远程= “true”;这样的形式被JS
- 形式处理作为POST请求提交到/运行路线
- 运行控制器设置为respond_to ajax
- c reate.js.erb文件应自动调用,因为控制器设置为处理JS。
这里是什么我咯困惑:
我需要一个阿贾克斯方法如果我有一个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,发布请求返回时,数据类型设置为脚本500错误。它可以正常工作,如果我将dataType设置为json,但部分仍然不呈现。
来源我咨询(我没有足够的声誉发布的所有链接):
- https://www.railstutorial.org/book/following_users#code-relationships_controller_ajax
- jQuery post to Rails
- 的Rails指南:使用JavaScript
- 许多其他SO帖子
在这里张贴之前,我已经花了很多时间。如果任何人都能指引我走向正确的方向,我会成为一个快乐的人。谢谢阅读。
在一个侧面说明 - 不要使用'redirect_to的:back'它依赖于浏览器发送一个[HTTP引用头。] (https://en.wikipedia.org/wiki/HTTP_referer) – max
谢谢Max!这解决了我的问题。 –