javascript - 将 Post 请求发送回 Sinatra 路由

标签 javascript ruby ajax sinatra

我有一个基本的 Sinatra/AJAX 应用程序,可以让两个图像相互竞争。该游戏有两个用户,在页面加载时都会提示他们登录。该应用程序的设置考虑了 MVC 框架。

我正在尝试实现一个数据库来存储比赛结果。我的数据库有三个表:games、players 和 player_games(因为一个游戏可以有多个玩家,一个玩家可以玩很多游戏)。

在 Controller 中我有三个主要路线。

POST 路由,在登录后创建两个玩家:

post '/' do
  @game = Game.create(player_1: params[:player1], player_2: params[:player2])
  return (@game).to_json
end

GET '/game/:id' 路由,加载统计 erb(只显示获胜的玩家和玩游戏所花费的总时间):

get '/game/:id' do
  @game = Game.find(params[:id])
  erb :stats
end

还有 POST '/stats' 路由,它保存游戏和统计数据并重定向回上面的 GET 请求:

post '/stats' do
  game = Game.find(params[:game_id])
  game.winner = params[:winner]
  game.play_time = params[:time]
  game.save!
  redirect '/game/' + params[:game_id]
end

在 JavaScript 文件中,当游戏结束时,我使用 jQuery 的 $.post 方法将统计数据发送到 POST '/stats' 路由。这会保存统计数据,但不会将游戏重定向到 GET '/game/:id' 路由。它会完全命中代码的 @game = Game.find(params[:id]) 部分,如果我这样设置发布路由,它甚至会打印“hello world”,但会不重定向到 GET '/game/:id' 路线:

get '/game/:id' do
  @game = Game.find(params[:id])
  erb :stats
  puts "hello world"
end

`D, [2014-04-29T19:48:51.723270 #3242] DEBUG -- :    (0.2ms)  BEGIN
D, [2014-04-29T19:48:51.729138 #3242] DEBUG -- :    (0.6ms)  UPDATE "games" SET "winner" = 'tim', "play_time" = 3, "updated_at" = '2014-04-29 19:48:51.724453' WHERE "games"."id" = 10
D, [2014-04-29T19:48:51.732144 #3242] DEBUG -- :    (2.6ms)  COMMIT
D, [2014-04-29T19:48:52.208625 #3245] DEBUG -- :   Game Load (1.4ms)  SELECT "games".* FROM "games" WHERE "games"."id" = $1 LIMIT 1  [["id", "10"]]
hello world`

最佳答案

因为$.post是异步的,所以不会重定向页面。服务器代码正在执行,但实际上不会执行 erb :stats 行。

这有点乱,但是在你的 $.post 之后,你可以做 window.location.href = "/game/"+ whatever_the_specific_game_id_is; 和 < em>那 将重定向您。

另外,请注意您的has_and_belongs_to_many 连接表。它可能应该按字母顺序命名。来自 ActiveRecord 文档:

Unless the join table is explicitly specified as an option, it is guessed using the lexical order of the class names. So a join between Developer and Project will give the default join table name of “developers_projects” because “D” precedes “P” alphabetically.

关于javascript - 将 Post 请求发送回 Sinatra 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23377288/

相关文章:

javascript - 谷歌地图:How to get points along the route in google maps,服务器端?

javascript - ajax 将数据从 javascript 发送到 python

javascript - 来自 ajax POST 的引导模式的下拉菜单

javascript - jquery ajax获取特殊字符(元音变音)

javascript - PHP: isset() 不检测 GET 变量

javascript - ownProps 缺少通过 mapStateToProps 添加的 Prop

javascript 交换和替换字符串

javascript - Summernote上传图片: onImageUpload and sendFile function not working

ruby - initialize 方法是 Ruby 中的内置方法吗?

sql - Ruby on Rails - 查询多个模型