I am working with Ruby on Rails, JavaScript and Simple Form and I have a problem adding Ruby code into a function in JavaScript.
我正在使用Ruby on Rails,JavaScript和Simple Form,我在将JavaScript代码添加到JavaScript函数中时遇到了问题。
My source code is:
我的源代码是:
$('#add_taxo').on('click',function() {
document.getElementById('okok').innerHTML += '<li class="list-group-item"> <%= taxonomies_select_tag( 'statistic[taxonomy]', Folders::Taxonomy, Folders::Taxonomy::TAXONOMY_KEY, level: 3, path: 'folders/taxonomies', include_blank: true, class: 'required form-control test_taxo')%> </li>';
alert("lklk");
});
This code doesn't work.
此代码不起作用。
3 个解决方案
#1
1
You can only use ruby code through the view/*.js/coffee.erb files via ajax. You can't use ruby in plain js/coffeescript files. If you need to pass data from the controller to the js side, then pass them through hidden field tags in your view through data attributes.
您只能通过ajax查看/ * .js / coffee.erb文件中的ruby代码。你不能在普通的js / coffeescript文件中使用ruby。如果需要将数据从控制器传递到js端,则通过数据属性将它们传递到视图中的隐藏字段标记。
#2
0
Try escaping the javascript in the ruby code, like this:
尝试在ruby代码中转义javascript,如下所示:
document.getElementById('okok').innerHTML += '<li class="list-group-item"> <%= j(taxonomies_select_tag( 'statistic[taxonomy]', Folders::Taxonomy, Folders::Taxonomy::TAXONOMY_KEY, level: 3, path: 'folders/taxonomies', include_blank: true, class: 'required form-control test_taxo'))%> </li>';
You can use either escape_javascript(...)
or j(...)
(as in the example).
您可以使用escape_javascript(...)或j(...)(如示例中所示)。
#3
0
make sure extension is .js.erb
and it's part of views folder.
确保扩展名是.js.erb,它是views文件夹的一部分。
If you want to do it through plain js then pass those variables through html
, for eg: hidden fields, html tag properties.
如果你想通过普通的js来做,那么通过html传递这些变量,例如:隐藏字段,html标签属性。
#1
1
You can only use ruby code through the view/*.js/coffee.erb files via ajax. You can't use ruby in plain js/coffeescript files. If you need to pass data from the controller to the js side, then pass them through hidden field tags in your view through data attributes.
您只能通过ajax查看/ * .js / coffee.erb文件中的ruby代码。你不能在普通的js / coffeescript文件中使用ruby。如果需要将数据从控制器传递到js端,则通过数据属性将它们传递到视图中的隐藏字段标记。
#2
0
Try escaping the javascript in the ruby code, like this:
尝试在ruby代码中转义javascript,如下所示:
document.getElementById('okok').innerHTML += '<li class="list-group-item"> <%= j(taxonomies_select_tag( 'statistic[taxonomy]', Folders::Taxonomy, Folders::Taxonomy::TAXONOMY_KEY, level: 3, path: 'folders/taxonomies', include_blank: true, class: 'required form-control test_taxo'))%> </li>';
You can use either escape_javascript(...)
or j(...)
(as in the example).
您可以使用escape_javascript(...)或j(...)(如示例中所示)。
#3
0
make sure extension is .js.erb
and it's part of views folder.
确保扩展名是.js.erb,它是views文件夹的一部分。
If you want to do it through plain js then pass those variables through html
, for eg: hidden fields, html tag properties.
如果你想通过普通的js来做,那么通过html传递这些变量,例如:隐藏字段,html标签属性。