home_controller.rb
class HomeController < ApplicationController
def index
@labels = ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'].to_json.html_safe
end
end
_main.js.erb
window.onload = function() {
var ctx = document.getElementById('fgm').getContext('2d');
console.log("<%= escape_javascript @labels %>");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: "<%= escape_javascript @labels %>",
浏览器控制台日志
["Red","Blue","Yellow","Green","Purple","Orange"]
浏览器调试
<script type="text/javascript">
window.onload = function() {
var ctx = document.getElementById('fgm').getContext('2d');
console.log("[\"Red\",\"Blue\",\"Yellow\",\"Green\",\"Purple\",\"Orange\"]");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: "[\"Red\",\"Blue\",\"Yellow\",\"Green\",\"Purple\",\"Orange\"]",
datasets: [{
label: '# of Votes',
这是我的问题:
labels: "[\"Red\",\"Blue\",\"Yellow\",\"Green\",\"Purple\",\"Orange\"]",
因为我需要不要将其用引号引起来,例如
labels: ["Red","Blue","Yellow","Green","Purple","Orange"],
答案 0 :(得分:2)
使用此:
@labels = ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'].to_json.html_safe
并像这样使用它,没有"
周围的内容,并且您不必对其进行转义(它已经被to_json和html_safe所代替):
console.log(<%= @labels %>);
labels: <%= @labels %>,
答案 1 :(得分:1)
以下代码应该可以工作
home_controller.rb
class HomeController < ApplicationController
def index
@labels = ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange']
# You don't need to use to_json and html_safe
end
end
_main.js.erb
window.onload = function() {
var ctx = document.getElementById('fgm').getContext('2d');
labels = <%= raw @labels %> # use raw method
console.log(labels);
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,