Gon变量在Ajax请求期间没有从rails控制器传递给js

时间:2022-12-01 21:33:56

I'm trying to create a jackpot betting site (just as a challenge). I have a method in my controller to update the pot when a user adds money to the pot. I display the pot total on the homepage and would like to update it with Ajax as soon as someone adds money to the pot. I'm using the gon gem to pass variables such as the pot total from my controller to my javascript. It works when the page is reloaded but not when the update method is called with ajax.

我正在尝试创建一个累积奖金投注站点(就像挑战一样)。我有一个方法在我的控制器中,当用户向底池添加钱时更新底池。我在主页上显示底池总数,并希望一旦有人向底池添加钱,就用Ajax更新它。我正在使用gon gem将变量(例如我的控制器中的总计)传递给我的javascript。它在重新加载页面时有效,但在使用ajax调用更新方法时却不起作用。

Heres my PagesController:

继承我的PagesController:

def home
  @jackpot = Jackpot.last
  gon.pot = @jackpot.pot
end

JackpotsController:

JackpotsController:

def update
  @jackpot = Jackpot.find(params[:id])
  if params.has_key?(:amount)
    @jackpot.update(pot: @jackpot.pot + params[:amount].to_f)
    gon.pot = @jackpot.pot
  end
  respond_to do |format| 
    format.js
  end
end

Javascript: (In the url the :id is hardcoded for now)

Javascript :(在url中:id现在是硬编码的)

$("#bet-btn").click(function() {
   $.ajax({
        type: "POST",
        url: "/jackpot/update/21",
        datatype: "json",
        success: function() {
          console.log("Pot size: " + gon.pot);
          updatePot();
        },
        error: function() {
          console.log("error")
        }
    });

});

});

This updates the donut progress bar for the pot

这会更新锅的甜甜圈进度条

function updatePot() {
  updateDonutChart('#jackpot-donut', gon.pot , true); 
}

Button to place bet: (amount also hardcoded)

下注按钮:(金额也硬编码)

 <%= link_to "Place Bet", update_pot_path(@jackpot, :amount => 
 0.1), method: :post,:remote => true, id: "bet-btn", class: "btn btn-info btn-lg" %>

I'm pretty new to rails and especially javascript/ajax so any help would be appreciated. Thanks!

我对rails很新,尤其是javascript / ajax,所以任何帮助都会受到赞赏。谢谢!

1 个解决方案

#1


1  

In the controller, simply respond to JSON:

在控制器中,只需响应JSON:

respond_to do |format|
  format.json { render json: { pot: @jackpot.pot } }
end

Specify the dataType when posting with $.ajax. Notice that the new data is bieng passed to the success function, so it's not gon.pot, but data.pot.

使用$ .ajax发布时指定dataType。请注意,新数据已被传递给成功函数,因此它不是gon.pot,而是data.pot。

$.ajax({
  dataType: "json",
  url: url,
  data: data,
  success: function(data) {
    console.log('pot', data.pot);
  }
});

#1


1  

In the controller, simply respond to JSON:

在控制器中,只需响应JSON:

respond_to do |format|
  format.json { render json: { pot: @jackpot.pot } }
end

Specify the dataType when posting with $.ajax. Notice that the new data is bieng passed to the success function, so it's not gon.pot, but data.pot.

使用$ .ajax发布时指定dataType。请注意,新数据已被传递给成功函数,因此它不是gon.pot,而是data.pot。

$.ajax({
  dataType: "json",
  url: url,
  data: data,
  success: function(data) {
    console.log('pot', data.pot);
  }
});