Sinatra AJAX重定向,为什么它不起作用?

时间:2015-06-06 09:21:19

标签: javascript ruby-on-rails ruby ajax

它进入重定向的URL控制器,但实际上并没有执行重定向。有什么想法吗?我已经包含了TML,JS文件和Ruby控制器文件。

controller.rb

get '/' do
  erb :welcome
end

post '/users/create' do
  byebug
  @player1 = User.new(name: params[:player1])
  @player2 = User.new(name: params[:player2])
  if @player1.save && @player2.save
      @race = Race.create
      @user_race = UserRace.create(player1_id: @player1.id, player2_id: @player2.id, race_id: @race.id)
      redirect to "/race/#{@race.id}"
  else
    @player1 = User.find_by_name(params[:player1])
    @player2 = User.find_by_name(params[:player2])
    @race = Race.create
    byebug
    @user_race = UserRace.create(player1_id: @player1.id, player2_id: @player2.id, race_id: @race.id)
    # byebug
      redirect to "/race/#{@race.id}"
  end
end

get '/race/:race_id' do
  @race = Race.find(params[:race_id])
  @user_race = UserRace.find_by_race_id(params[:race_id])
  # byebug
  @player1 = User.find(@user_race.player1_id)
  @player2 = User.find(@user_race.player2_id)
  erb :race
end

put '/race' do
  # byebug
  @race = Race.find(params[:race_id])
  @race.winner = User.find(params[:winner_id])
  @race.loser_index = params[:loser_index]
  @race.save
  redirect to "/winner/#{params[:race_id]}"
end

get '/winner/:race_id' do
  @race = Race.find(params[:race_id])
    byebug
  erb :winner
end

正在调用的JS函数。

function parseWinner(player_track, loser_index) {
var race_id = $("#race").data("race-id")
var player1_id = $("#race").data("playerone-id")
var player2_id = $("#race").data("playertwo-id")
if (player_track === $cells1) {
  // debugger
  $.ajax({
    type: "PUT",
    url: "/race",
    data: {"race_id": race_id, "winner_id": player1_id, "loser_index": loser_index, "time_spent": this.time}
  }).done(function(e){
    // e.preventDefault();
    window.location = "/winner/" + race_id
  })
}
else {
  $.ajax({
    type: "PUT",
    url: "/race",
    data: {"race_id": race_id, "winner_id": player2_id, "loser_index": loser_index}
  }).done(function(e){
    // e.preventDefault();
    window.location = "/winner/" + race_id
  })
}

HTML文件

<h1 id="race" data-race-id=<%= @race.id %> data-playerone-id=<%= @player1.id %> data-playertwo-id=<%= @player2.id %>>Javascript Racer</h1>

<table class="racer_table">
  <link rel="stylesheet" type="text/css" href="/css/normalize.css">
  <link rel="stylesheet" type="text/css" href="/css/style.css">
  <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script type="text/javascript" src="/js/racer.js"></script>
  <!-- <p>We have a winner!!!!</p> -->
  <div id="banner"></div>
  <tr id="player1_strip">
    <% 20.times do |x| %>
    <td></td>
    <% end %>
  </tr>
  <tr id="player2_strip">
    <% 20.times do |x| %>
    <td></td>
    <% end %>
  </tr>

</table>

0 个答案:

没有答案