简体   繁体   English

如何将变量从javascript(咖啡)传递到Rails控制器?

[英]How to pass a variable from javascript (coffeescript) to rails controller?

I guess this should be simple, but I can't figure it out 我想这应该很简单,但我无法弄清楚

I my view there is a link that I want to trigger some ajax: 我认为有一个链接想要触发一些ajax:

link_to( "#{sir.sir_id}" , '#', :data => {'sir-id' => sir.id}, remote: true ),

In my coffeescript I can get the value of the data-attribute in the link like so: 在我的coffescript中,我可以通过以下链接获取数据属性的值:

$ ->
  $("a[data-sir-id]").click ->
  data_sir_id = $(this).data("sir-id")

So I need the value of that variable (data_sir_id) in my controller, so I can get its associated model objects and render them in the same view 因此,我需要在控制器中使用该变量的值(data_sir_id),以便获取其关联的模型对象并将其呈现在同一视图中

How could I achieve that? 我该如何实现?

You don't need to store your data in a data attribute and to make an ajax call when clicking on the link: link_to provides you a great way to make link and to pass parameters. 单击链接时,您不需要将数据存储在data属性中并进行ajax调用: link_to为您提供了一种进行链接和传递参数的好方法。

And by using, remote: true , it will do an ajax call without any other configuration. 通过使用remote: true ,它将进行ajax调用而无需任何其他配置。

link_to("#{sir.sir_id}", path_to_the_controller_action(sir_id: sir.id), remote: true)

Then, in your controller action, your data will be accessible in params[:sir_id] 然后,在您的控制器操作中,您的数据将可以通过params[:sir_id]

Here in link_to you have passed url as '#' , so if you have a particular action that you can add then you can go by above way link_to您已将url传递为'#' ,因此,如果您有可以添加的特定操作,则可以按照上述方法进行操作

else you can use the following: 否则,您可以使用以下命令:

To specify link in view, you can use it as 要在视图中指定链接,可以将其用作

link_to "#{sir.sir_id}", '#', remote: true, 'sir-id' => sir.id, class: 'sir_id_link'

In coffeescript: 在咖啡脚本中:

$ ->
  $("sir_id_link").live "click", ->
  data_sir_id = $(@).attr("sir-id")
  $.ajax
    url: any_url
    type: "PUT"
    data:
      sir_id: data_sir_id
    success: (data) ->
      ...

Now in your controller action, you can access it as params[:sir_id]. 现在,在控制器操作中,您可以将其作为params [:sir_id]进行访问。

Hope this would help you. 希望这对您有帮助。

Thanks. 谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM