使用script标记时使用ejs

pxyaymoc  于 2021-08-13  发布在  Java
关注(0)|答案(1)|浏览(446)

我在node.js/express+postgresql和ejs中工作。
我想在标记脚本中插入<%=result.dis%>。我从db查询得到的结果。
我试着这样做:

var vPlayer = `<%-JSON.stringify(avg.mark)%>`;
console.log(vPlayer);

或者这个:

const div = document.createElement('div');
div.innerText = `<%=avg.mark %>`
console.log(div);

但这不管用。我的完整代码,我想画一个图表

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

<% avg_t.rows.forEach(function(avg){%>
  <script type="text/javascript">
    var vPlayer = `<%-JSON.stringify(avg.mark)%>`;
    console.log(vPlayer);

    const div = document.createElement('div');
    div.innerText = `<%=avg.mark %>`
    console.log(div);

    google.charts.load('current', {
      'packages': ['corechart']
    });
    google.charts.setOnLoadCallback(drawChart);

    function drawChart() {
      var data = new google.visualization.DataTable();
      data.addColumn('string', 'Topping');
      data.addColumn('number', 'Slices');
      data.addRows([
        ['Mushrooms', vPlayer],
        ['Mu112', div],
        ['Onions', 1],
      ]);
      var barchart_options = {
        title: 'Barchart: How Much Pizza I Ate Last 
        Night ',width:400,height:300,legend: '
        none '};
        var barchart = new google.visualization.BarChart(document.getElementById('barchart_div'));
        barchart.draw(data, barchart_options);
      }
  </script>
<%} ) %>
prdp8dxp

prdp8dxp1#

有两行我完全不懂,但你是这段代码的所有者:

['Mushrooms', vPlayer /*I don't understand this*/],
['Mu112', div/*I don't understand this*/],

新方法:

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
  let rows = JSON.parse('<%= JSON.stringify(avg_t.rows) %>');
  let players = [];

  rows.forEach(function(avg, i) {
    players.push(avg.mark);

    let div = document.createElement('div');
    div.innerText = avg.mark; //I don't know 
    div.setAttribute("id", `barchart_div${i}`);
    /*You should append this new div into a specific element*/
  });

  google.charts.load('current', {
    'packages': ['corechart']
  });

  function drawChart() {
    players.forEach(function(vPlayer, i) {
      let div = document.getElementById(`barchart_div${i}`);
      let data = new google.visualization.DataTable();
      data.addColumn('string', 'Topping');
      data.addColumn('number', 'Slices');
      data.addRows([
        ['Mushrooms', vPlayer /*I don't understand this*/],
        ['Mu112', div/*I don't understand this*/],
        ['Onions', 1],
      ]);
      var barchart_options = {
        title: 'Barchart: How Much Pizza I Ate Last Night ',
        width: 400,
        height: 300,
        legend: 'none'
      };
      var barchart = new google.visualization.BarChart(div);
      barchart.draw(data, barchart_options);
    });
  }

  google.charts.setOnLoadCallback(drawChart);
</script>

相关问题