简体   繁体   中英

Pug - Access data from server in pug script(type='text/javascript')

I am trying to load data from the server in my pug template.

My route looks like the following:

app.get('/serverdata', async(req, res) => {

  const chartData = []
  for (const i = 0; i < 7; i++) {
    chartData.push(Math.random() * 50)
  }

  const result = JSON.stringify(chartData)

  res.render('serverdata', {
    result,
  })
})

My pug template looks like the following:

  .row
    .col-md-12
      .card
        .embed-responsive.embed-responsive-16by9
          canvas#myNewChart(style='display: block; width: 1000px; height: 500px;', width='1000', height='500')      

block specific-js
  script(type='text/javascript', src="js/plugins/chart.js") 
  script(type='text/javascript').
    var data = {
      labels: ["January", "February", "March", "April", "May", "June", "July"],
      datasets: [
        {
          label: "My First dataset",
          fillColor: "rgba(220,220,220,0.2)",
          strokeColor: "rgba(220,220,220,1)",
          pointColor: "rgba(220,220,220,1)",
          pointStrokeColor: "#fff",
          pointHighlightFill: "#fff",
          pointHighlightStroke: "rgba(220,220,220,1)",
          data: result //here I am getting the error
        }
      ]
    };

    var ctx = document.getElementById("myChart").getContext("2d");
    var myNewChart = new Chart(ctx).Line(data);

My error is within my view file:

serverdata:13 Uncaught ReferenceError: result is not defined
    at serverdata:13

Any suggestions how to load server data in the script. tag of my pug file?

I appreciate your replies!

I think you are mixing different contexts. The line that gives you an error is executed in the browser, and in that context, there is no variable named result .

Since you have a endpoint /serverdata on your server in place, all you need to load and parse the data from that URL. Details depend on what kinds of JavaScript libraries you are using, but with jQuery getJSON :

$.getJSON("/serverdata", function(data) {
    /* Update your chart by using 'data' */
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM