Rails 4:将变量传递给 javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28870567/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails 4: Passing variables to javascript
提问by Seph Cordovano
I've tried numerous methods and followed Ryan Bates'guide but no matter what I do I still get undefined.
我尝试了多种方法并遵循了Ryan Bates 的指南,但无论我做什么,我仍然没有定义。
application.html.erb
应用程序.html.erb
<body>
<%= content_tag :div, id: 'trackers', data: {trackers: User.count} do %>
<% end %>
</body
application.js.erb
应用程序.js.erb
var datadump = ($('#trackers').data('trackers'))
console.log(datadump)
//returns undefined in console
Viewing page source I can see the variable
查看页面源我可以看到变量
<div data-trackers="2" id="trackers">
I'm passing User.count for now just to keep it simple but I'll need to be passing @trackers_count which is instantiated in a before_action in the application controller. I should be able to sort that out though once I figure out the problem here. Any suggestions?
我现在传递 User.count 只是为了简单起见,但我需要传递 @trackers_count,它在应用程序控制器的 before_action 中实例化。我应该能够解决这个问题,但一旦我在这里找出问题。有什么建议?
UPDATE- I've simplified all variables down to just trackers, instead of trackers_count to prevent any errors from syntax and updated code here to reflect that.
更新- 我已将所有变量简化为仅跟踪器,而不是 trackers_count 以防止任何语法错误,并在此处更新代码以反映这一点。
ANSWER UPDATE- I selected the correct answer because if you want to pass any variables ASIDE FROM CURRENT_USER those methods worked perfectly. However, you can't access anything with current_user in JS because it loads before the window, so it can't know who the current_user is. It's a real pain but I just did it the long way and accessed the info I need through passing in json and an ajax requests.
ANSWER UPDATE- 我选择了正确的答案,因为如果你想从 CURRENT_USER 传递任何变量,这些方法工作得很好。但是在JS中不能用current_user访问任何东西,因为它是在window之前加载的,所以它不知道current_user是谁。这是一个真正的痛苦,但我只是做了很长的路,并通过传入 json 和 ajax 请求访问了我需要的信息。
回答by Guru
I used to do:
我曾经做过:
var my_var = <%= User.count %>
console.log(my_var)
If it is an integer this works just fine. If, however, you want to pass objects, then use:
如果它是一个整数,这工作得很好。但是,如果您想传递对象,请使用:
var my_var = JSON.parse(('<%= (@Users.count) == 0 ? "[]" : Users.first(10).to_json %>')
console.log(JSON.stringify(my_var))
回答by bondarenko.dev
You forgot about document ready. Try:
你忘记了文件准备好了。尝试:
$(function(){
var datadump = ($('#trackers').data('trackers'));
console.log(datadump)
});
Or for provide data from Rails to JS use Gon gem https://github.com/gazay/gon
或者从 Rails 向 JS 提供数据使用 Gon gem https://github.com/gazay/gon
回答by Mavrick Laakso
Stumbled here from google. In my case, I was trying to pass an array of objects to a js.erb, which triggered an event a front end component listened to. For anyone from google, I solved this issue by doing the following:
从谷歌偶然发现这里。就我而言,我试图将一组对象传递给 js.erb,这会触发前端组件侦听的事件。对于谷歌的任何人,我通过执行以下操作解决了这个问题:
In my controller.rb:
在我的 controller.rb 中:
@payload = []
array.each do |a|
temp = {
foo: a.id,
bar: a.relation.relation
}
@payload << temp
end
in my js.erb:
在我的 js.erb 中:
$(document).trigger('event', { data: <%= @payload.to_json.html_safe %> })
in my component.js:
在我的 component.js 中:
$(document).on('event', (e, data) => {
console.log(data) //should be array of objects in proper format
})
Hope this helps someone!
希望这对某人有帮助!
回答by Jose Paez
Thiscould help you.
这可以帮助你。
For me, I wanted to turn this array
对我来说,我想把这个数组
@dates = ["2018-12-24", "2018-12-25", "2018-12-26", "2018-12-27", "2018-12-28"]
into a variable in Javascript. I tried the basic:
到 Javascript 中的变量。我尝试了基本的:
var dates = <%= @dates.join(", ") %>
alert(my_var)
This alerted this exact text:
这提醒了这个确切的文本:
1995
I have no clue why.
我不知道为什么。
Since it wasn't working I tried Guru's solutions up there by copying and pasting, but it was worse now I had an error coming up in my code. Finally I got Guru's solution to work like this:
由于它不起作用,我通过复制和粘贴尝试了 Guru 的解决方案,但现在更糟的是我的代码出现错误。最后我得到了 Guru 的解决方案,可以这样工作:
(the print embedded ruby open and close worked outside the JSON.parse() and there was a missing ")" )
(打印嵌入的 ruby 打开和关闭在 JSON.parse() 之外工作,并且缺少 ")" )
var dates = <%= JSON.parse(@dates.join(", ").to_json)%>
alert(dates)
But even though it didn't crash, want to guess what it alerted?
但即使它没有崩溃,想猜猜它发出了什么警报?
Yeap, you guessed it:
是的,你猜对了:
1995
So I gave up and I used a work around:
所以我放弃了,我使用了一个解决方法:
In my view edit.html.erb
在我看来edit.html.erb
<div class="dates"><%= @dates.join(", ") %></div>
<script>
var dates = $(".dates").text()
alert(dates)
$(".datepicker").val(dates)
</script>
That allowed me to feed the variable, therefore alert the correct data and set the Datepicker's input with the correct information. I'm still bugged for not being able to solve the hole 1995 problem. If someone could be so kind as to explain, I would really appreciate it. Hope this helps and have a great day!
这允许我提供变量,因此提醒正确的数据并使用正确的信息设置 Datepicker 的输入。我仍然因为无法解决 1995 年的洞问题而苦恼。如果有人能这么好心解释一下,我将不胜感激。希望这会有所帮助,祝您有美好的一天!