简体   繁体   English

如何在公共JS文件中使用通过Express res.render发送的JSON

[英]How to use JSON sent via Express res.render in a public JS file

Thanks in advance for your help. 在此先感谢您的帮助。 I have a question that has been bothering me and I am sure it is absurdly simple. 我有一个困扰我的问题,我相信这很简单。

On an app.get request I am calling an external api from express and then using res.render to send a jade file and the json. 在一个app.get请求中,我从express调用一个外部api,然后使用res.render发送一个jade文件和json。

I can successfully manipulate this data within jade files, and JavaScript written directly in the jade file. 我可以在jade文件中成功处理这些数据,并且可以直接在jade文件中编写JavaScript。

However, I cannot for the life of me figure out how to manipulate this JSON from a JavaScript file referenced from the outputted HTML. 但是,我终生无法弄清楚如何从输出的HTML引用的JavaScript文件中处理此JSON。

For example: 例如:

router.get('/dashboard', function (req, res, next) {

  // Call the external api and get data.
  // Parse the data

  res.render('dashboard', {
      data: data
  });

});

The dashboard.jade file then uses this data to do cool stuff. 然后,dashboard.jade文件使用此数据来完成一些很酷的事情。

if #{data.isNew} === true {do cool stuff}

I have also written some JavaScript that uses this data directly into the dashboard.jade file itself. 我还编写了一些JavaScript,将这些数据直接用于dashboard.jade文件本身。 But, I would prefer to write and use this JavaScript in a file called scripts.js that is referenced from the Jade file. 但是,我更愿意在从Jade文件引用的名为scripts.js的文件中编写和使用此JavaScript。

script(src='scripts.js')

I cannot access this data - I have tried multiple syntax to try to get it to work but have miserable failed. 我无法访问此数据-我尝试了多种语法来尝试使其正常工作,但惨遭失败。

My question is this, how do I work with JSON that has been res.rendered() to a view from within a JS file referenced from that rendered view? 我的问题是,我该如何处理已将res.rendered()转换为视图的JS文件中的JSON?

You need to declare a variable inside dashboard.jade that then uses interpolation to output the data into a string: 您需要在dashboard.jade中声明一个变量,然后使用插值将数据输出到字符串中:

 script.
   var myData = #{JSON.stringify(data)};

The Jade engine will output that as a valid string that can then be used by any script loaded on that page. Jade引擎会将其输出为有效字符串,然后供该页面上加载的任何脚本使用。

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

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