問題:部分不會在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!這解決了我的問題。 –