Rails中的Ajax POST请求错误

时间:2016-11-28 07:11:48

标签: javascript jquery ruby-on-rails ajax

我正在尝试在简单的Rails应用程序中首次实现Ajax,主要是通过本教程帮助:

Integrating Ajax and Rails

我的应用程序有一个特定的显示视图,我想显示一个排行榜,用于呈现用户及其记录的列表以及可以创建新用户/记录的表单。

我想通过Ajax实现这一点,但每次我尝试提交Ajax请求时,都会收到500错误,指向下面的JQuery行并抛出'Failed to load resource'消息。

xhr.send( ( options.hasContent && options.data ) || null );  

我试图改变一些事情但没有成功,包括在表单中使用remote:true并直接使用JQuery发出Ajax请求。你能指点我这里潜在的问题吗?相关代码下方:

leaderboards_Controller 显示操作会显示相关的排行榜

  def show
   @leaderboard = Leaderboard.find(params[:id])
   @leaders = @leaderboard.leaders
   @leader = Leader.new(persisted_time: @persisted_time)
  end

排行榜/ show.html.erb

  <%= simple_form_for([@leaderboard, @leader], html: { class: 'form-inline', id:'leader-form' }) do |f| %>
    <%= f.error_notification %>
    <div class="form-inputs">
      <%= f.input :name, :label => false, :placeholder => "Your name here", :required => true, :autofocus => true %>
      <%= f.input :record_time, :label => "Your record", input_html: {readonly: ''} %>
      <%= f.button :submit %>
    </div>
  <% end %>

  <ul>
  <% @leaders.each do |leader| %>
    <li>
      <%= leader.name %> |
      <strong>record: </strong><%= leader.record_time %> <br />
    </li>
  <% end %>
  </ul>

leaders_Controller 我打算在提交上面的表单时将Ajax请求发送到此控制器中的create操作

class LeadersController < ApplicationController
  before_action :set_leader, only: [:show, :edit, :update, :destroy]
  before_action :set_leaderboard, only: [:create, :new]

  def index
    @leaders = Leader.all
  end

  def show
  end

  def new
  end

  def edit
  end

  def create
     @leaderboard = Leaderboard.find(params[:leaderboard_id])
     @leader = Leader.new(leader_params)
     @leader.leaderboard_id = @leaderboard.id
     respond_to do |format|
        if @leader.save
          format.json { render json: @leader, status: :created}
        else
          format.json { render json: @leader.errors, status: :unprocessable_entity }
        end
     end
  end

  def update
    @leader.update_attributes(leader_params)
  end

  def destroy
    @leader.destroy
  end

  private
    def set_leader
      @leader = Leader.find(params[:id])
    end

    def set_leaderboard
      @leaderboard = Leaderboard.find(params[:leaderboard_id])
    end

    def leader_params
      params.require(:leader).permit(:name, :record_time, :leaderboard_id)
    end
end

assets / javascripts / leaders.js 我正在执行Ajax请求的JS文件

$(function(){
  $("form").submit(function(event){
  event.preventDefault();

  var action = $(this).attr('action');
  var method = $(this).attr('method');

  var name = $(this).find('#leader_name').val();
  var record_time = $(this).find('#leader_record_time').val();

  $.ajax({
    method: method,
    url: action,
    data: { name: name, record_time: record_time }
  });

  });
});

和路线

  resources :leaderboards, shallow: true do
   resources :leaders
  end

我显然没有得到关于Ajax的东西。如果你指出我正确的方向,我会很感激。

这是我在提交表单后在控制台中获得的输出

jquery.self-bd7ddd3….js?body=1:10255 POST http://localhost:3000/leaderboards/1/leaders 500 (Internal Server Error)

这导致了JQuery脚本中的这一行:

xhr.send( ( options.hasContent && options.data ) || null );

并产生:

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

和服务器日志

         Started POST "/leaderboards/1/leaders" for ::1 at 2016-11-28 21:42:24 +1100
Processing by LeadersController#create as JS
  Parameters: {"utf8"=>"✓", "leader"=>{"name"=>"9089sdas8dds", "persisted_time"=>"5"}, "commit"=>"S", "leaderboard_id"=>"1"}
  Leaderboard Load (0.5ms)  SELECT  "leaderboards".* FROM "leaderboards" WHERE "leaderboards"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  CACHE (0.0ms)  SELECT  "leaderboards".* FROM "leaderboards" WHERE "leaderboards"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
   (0.2ms)  BEGIN
  Leaderboard Load (0.4ms)  SELECT  "leaderboards".* FROM "leaderboards" WHERE "leaderboards"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  SQL (2.6ms)  INSERT INTO "leaders" ("name", "persisted_time", "leaderboard_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id"  [["name", "9089sdas8dds"], ["persisted_time", "5"], ["leaderboard_id", 1], ["created_at", 2016-11-28 10:42:24 UTC], ["updated_at", 2016-11-28 10:42:24 UTC]]
   (2.2ms)  COMMIT
Completed 201 Created in 15ms (Views: 0.8ms | ActiveRecord: 5.9ms)


Started POST "/leaderboards/1/leaders" for ::1 at 2016-11-28 21:42:27 +1100
Processing by LeadersController#create as JS
  Parameters: {"utf8"=>"✓", "leader"=>{"name"=>"9089sdas8dds", "persisted_time"=>"5"}, "commit"=>"S", "leaderboard_id"=>"1"}
  Leaderboard Load (0.5ms)  SELECT  "leaderboards".* FROM "leaderboards" WHERE "leaderboards"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  CACHE (0.0ms)  SELECT  "leaderboards".* FROM "leaderboards" WHERE "leaderboards"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
   (0.7ms)  BEGIN
  Leaderboard Load (0.5ms)  SELECT  "leaderboards".* FROM "leaderboards" WHERE "leaderboards"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  SQL (1.9ms)  INSERT INTO "leaders" ("name", "persisted_time", "leaderboard_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id"  [["name", "9089sdas8dds"], ["persisted_time", "5"], ["leaderboard_id", 1], ["created_at", 2016-11-28 10:42:27 UTC], ["updated_at", 2016-11-28 10:42:27 UTC]]
   (0.5ms)  COMMIT
Completed 201 Created in 14ms (Views: 1.0ms | ActiveRecord: 4.2ms)


Started POST "/leaderboards/1/leaders" for ::1 at 2016-11-28 21:42:29 +1100
Processing by LeadersController#create as JS
  Parameters: {"utf8"=>"✓", "leader"=>{"name"=>"9089sdas8dds", "persisted_time"=>"5"}, "commit"=>"S", "leaderboard_id"=>"1"}
  Leaderboard Load (0.6ms)  SELECT  "leaderboards".* FROM "leaderboards" WHERE "leaderboards"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  CACHE (0.0ms)  SELECT  "leaderboards".* FROM "leaderboards" WHERE "leaderboards"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
   (0.2ms)  BEGIN
  Leaderboard Load (0.6ms)  SELECT  "leaderboards".* FROM "leaderboards" WHERE "leaderboards"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  SQL (2.3ms)  INSERT INTO "leaders" ("name", "persisted_time", "leaderboard_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id"  [["name", "9089sdas8dds"], ["persisted_time", "5"], ["leaderboard_id", 1], ["created_at", 2016-11-28 10:42:29 UTC], ["updated_at", 2016-11-28 10:42:29 UTC]]
   (2.3ms)  COMMIT
Completed 201 Created in 14ms (Views: 0.7ms | ActiveRecord: 6.0ms)

2 个答案:

答案 0 :(得分:1)

尝试添加

respond_to(:js)

在你创建方法的最后。

是的,请使用remote: true

答案 1 :(得分:1)

请更新您的代码,如下所示。

<强> show.html.erb

<%= simple_form_for([@leaderboard, @leader],remote: true, html: { class: 'form-inline', id:'leader-form' }) do |f| %>
    <%= f.error_notification %>
    <div class="form-inputs">
      <%= f.input :name, :label => false, :placeholder => "Your name here", :required => true, :autofocus => true %>
      <%= f.input :record_time, :label => "Your record", input_html: {readonly: ''} %>
      <%= f.button :submit %>
    </div>
  <% end %>

  <ul>
  <% @leaders.each do |leader| %>
    <li>
      <%= leader.name %> |
      <strong>record: </strong><%= leader.record_time %> <br />
    </li>
  <% end %>
  </ul>

<强> leaders_Controller

def create
   @leaderboard = Leaderboard.find(params[:leaderboard_id])
   @leader = Leader.new(leader_params)
   @leader.leaderboard_id = @leaderboard.id
   respond_to do |format|
    if @leader.save
      format.json { render json: @leader, status: :created}
    else
      format.json { render json: @leader.errors, status: :unprocessable_entity }
    end 
   end 
  end

<强>资产/ Javascript角/ leaders.js

$(function(){    
return $("#your-form-id").on("ajax:success", function(e, data, status, xhr) {
            e.preventDefault();
            // success code 
        }).on("ajax:error", function(e, xhr, status, error) {
            // error code
        });
});