2017-04-11 76 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都是对的。 –