简体   繁体   English

Pug-在Pug脚本中从服务器访问数据(type ='text / javascript')

[英]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. 有关如何在script.加载服务器数据的任何建议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 . 在浏览器中执行向您显示错误的行,并且在这种情况下,没有名为result变量。

Since you have a endpoint /serverdata on your server in place, all you need to load and parse the data from that URL. 由于/serverdata上已经有一个端点/serverdata ,因此您需要从该URL加载和解析数据。 Details depend on what kinds of JavaScript libraries you are using, but with jQuery getJSON : 详细信息取决于您使用的是哪种JavaScript库,但是使用jQuery getJSON

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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