Google 图表 - 在 javascript 中将数据作为变量传递

Google Charts - passing data as variable in javascript

我正在使用 google 图表在健康应用程序中创建报告。由于应用程序的工作方式,我必须在 XSL 文档中为图表定义数据,然后使用 javascript 来获取和使用该数据。我无法 运行 XSL 中的 javascript 内联 - 应用程序阻止了它。

XSL 工作正常并给我以下信息:-

<div id="mydata" style="display:none;">
        [{c:[{v: new Date(2020,3,21)}, {v:94.05}]},
         {c:[{v: new Date(2020,3,29)}, {v:94.3}]},
         {c:[{v: new Date(2020,4,5)}, {v:95}]},]
</div>

我的 javascript 看起来像这样:-

  google.charts.load('current', {'packages':['corechart']});
  google.charts.setOnLoadCallback(drawChart);
  var mydata=$("#mydata").text()
  var mydata=mydata.replace("},]", "}]");
  var myconfig="{cols: [{id: 'Date', label: 'Date', type: 'date'},{id: 'Weight', label: 'Weight', type:'number'}],rows: " + mydata + "}"


function drawChart() {
    var data = new google.visualization.DataTable(myconfig);



    var options = {
      title: 'Patient Weight',
      curveType: 'function',
      legend: { position: 'bottom' }
    };

    var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));

    chart.draw(data, options);
  }

问题是它不起作用。我得到:

Uncaught (in promise) SyntaxError: Unexpected token c in JSON at position 0
    at JSON.parse (<anonymous>)
    at gvjs_Li (jsapi_compiled_default_module.js:55)
    at new gvjs_L (jsapi_compiled_default_module.js:161)
    at drawChart (<anonymous>:8:20)

如果我从 myconfig 中复制值并将其粘贴到 google 可视化中,它会完美运行。这是生成的 myconfig 变量:-

 cols: [{id: 'Date', label: 'Date', type: 'date'},{id: 'Weight', label: 'Weight', type:'number'}],rows: 
        [{c:[{v: new Date(2020,3,21)}, {v:94.05}]},{c:[{v: new Date(2020,3,29)}, {v:94.3}]},{c:[{v: new Date(2020,4,5)}, {v:95}]}]}

这让我抓狂。请帮忙!

更新:

终于破解了!!

我也将 cols 定义放入 DIV 中,并在所有内容周围加上引号,按照建议删除了 "new",最终它起作用了!

我有时会使用这种方法,这是我发现的。

当您对数据进行硬编码时它起作用的原因,
您正在将对象传递给数据 table。

但是当数据来自XSL时,它是一个字符串。

首先,所有对象键都必须用引号引起来。
其次,您不能在日期上使用 new 运算符。
你必须使用 google 的 date string representation

尝试从 XSL 中按如下方式格式化数据...

[{"c":[{"v": "Date(2020,3,21)"}, {"v":94.05}]},
     {"c":[{"v": "Date(2020,3,29)"}, {"v":94.3}]},
     {"c":[{"v": "Date(2020,4,5)"}, {"v":95}]}]

注意:关于逗号,下面是我用来防止最后一个逗号的xsl...

<xsl:if test="position() != last()">,</xsl:if>