将 ruby​​ 变量传递给 javascript (Ruby on Rails)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17520177/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 08:37:48  来源:igfitidea点击:

passing ruby variables to javascript (Ruby on Rails)

javascriptjqueryruby-on-rails

提问by Syed Daniyal Shah

I have a list of medicines and a list of vaccinations that I am extracting from tables medicines and vaccinations respectively. The list of medicines is of the format medicine_name and so is the list of vaccinations. I store both of these in vars using this piece of code.

我有一份药物清单和一份疫苗接种清单,我分别从药物和疫苗接种表中提取。药物列表的格式为medicine_name,疫苗接种列表也是如此。我使用这段代码将这两个存储在 vars 中。

var injections=<%=@injections%>;
var medicines=<%=@medicines%>;

In my view I have select tags for medicines and injections but when I try to append these vars to the respective tags using the following code. I don't get any results please help

在我看来,我为药物和注射剂选择了标签,但是当我尝试使用以下代码将这些变量附加到相应的标签时。我没有得到任何结果请帮忙

$('.addmedicines').click(function()
   $('.medicines').append(medicines);


});
$('.addinjections').click(function(){
   $('.injections').append(injections);
});

Here .injections is the class assigned to select tag for vaccinations. .medicines is the class assigned to select tag for medicines. And .addmedicines and .addinjections are html buttons.

这里 .injections 是分配给选择疫苗接种标签的类。.medicines 是分配给选择药物标签的类。.addmedicines 和 .addinjections 是 html 按钮。

EDITED:

编辑:

When I try to display both injections and medicines in javascript they display like this:

当我尝试在 javascript 中显示注射和药物时,它们显示如下:

Medicines:

药物:

<option>Med1</option><option>Med2</option><option>Med3</option><option>Med4</option>

Injections:

注射:

<option>i1</option><option>i2</option><option>i3</option><option>i4</option>

回答by Salil

var injections= '<%=@injections%>';
var medicines='<%=@medicines%>';

回答by Blue Smith

You can use Rails helper array_or_string_for_javascript, or just simply call to_json:

您可以使用 Rails 助手array_or_string_for_javascript,或者只是简单地调用to_json

var injections = <%= array_or_string_for_javascript(@injections) %>;
var medicines = <%= array_or_string_for_javascript(@medicines) %>;

// OR

var injections = <%= @injections.to_json %>;
var medicines = <%= @medicines.to_json %>;

回答by ahnbizcad

You're missing a {after the first function

{在第一个函数之后错过了

Should be:

应该:

$('.addmedicines').click(function(){  // <-- right here :)
   $('.medicines').append(medicines);


});
$('.addinjections').click(function(){
   $('.injections').append(injections);
});

What you have:

你有什么:

$('.addmedicines').click(function()   // <-- right here :)
   $('.medicines').append(medicines);


});
$('.addinjections').click(function(){
   $('.injections').append(injections);
});