ROR:如何在不重新加载浏览器的情况下从控制器获取参数

ROR:How can I get the params from controller without reloading the browser?

本文关键字:浏览器 情况下 参数 获取 控制器 加载 新加载 ROR      更新时间:2023-09-26

我现在正在使用一些gmap API,我通过gem"gon"传递lat和log。由于我希望标记是最新的,我需要最新的lat和log。如何在不重新加载整个页面的情况下将params从controller传递到view.html?

控制器.rb

@targetrecords.each do |targetrecords|
  pnts[i][0]=targetrecords.latitude
  pnts[i][1]=targetrecords.longitude
  pnts[i][2]=targetrecords.address
  pnts[i][3]=targetrecords.created_at
end
gon.pnts=pnts

index.html.erb

<script type="text/javascript">
var centlat = (gon.pnts[0][0]+gon.pnts[1][0]+gon.pnts[2]  
               [0]+gon.pnts[3][0])/4;
var centlng = (gon.pnts[0][1]+gon.pnts[1][1]+gon.pnts[2]   
               [1]+gon.pnts[3][1])/4
var map = new google.maps.Map(document.getElementById('map'), {
   zoom: 14,
   center: new google.maps.LatLng(centlat,centlng),
   mapTypeId: google.maps.MapTypeId.ROADMAP
});
</script>

视图中还有更多,但只是一些类似的东西,我希望它通过点击或其他方式更新。

使用gem-gon,如果您正确遵循设置,您可以在控制器中执行此操作:

def your_action
  gon.your_variable = your_ruby_variable
end

现在您可以在javascript中访问它。要尝试它,你可以做:

console.log(gon.your_variable)

您应该能够在浏览器的控制台中看到它。

您也可以使用ajax请求,但既然您询问了gon,这应该可以工作。

编辑:要在加载第一个页面后获得更新,您可以使用gon watchhttps://github.com/gazay/gon/wiki/Usage-gon-watch

相关文章: