2017-04-11 79 views
1

問題:部分不會在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,但部分仍然不呈現。

來源我諮詢(我沒有足夠的聲譽發佈的所有鏈接):

在這裏張貼之前,我已經花了很多時間。如果任何人都能指引我走向正確的方向,我會成爲一個快樂的人。謝謝閱讀。

回答

1

您需要設置您的控制器以響應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 

若沒有通過一個塊將觸發渲染create.erb.js的軌道默認行爲。

如果我有create.js.erb文件,是否需要.ajax方法?

不,您正在使用the Rails UJS driver已發送ajax請求。否則,日誌中的響應類型將是:html

其他SO問題提到設置dataType =「script」。據我所知,我不應該需要這個文件。

你是對的。 Rails UJS默認使用JavaScript接受類型頭。它只有在你想要一個JSON響應時,例如你需要設置dataType。

+0

在一個側面說明 - 不要使用'redirect_to的:back'它依賴於瀏覽器發送一個[HTTP引用頭。] (https://en.wikipedia.org/wiki/HTTP_referer) – max

+0

謝謝Max!這解決了我的問題。 –

1

您的控制器缺少format.js。當您發出AJAX請求時,Rails會查找它。

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 
1

剛剛嘗試這一點在你的控制器的創建方法:

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"} 

希望這有助於..

+0

感謝Mayank!你和Max都是對的。 –

相關問題