如何将 JSON 数据从 express 传递到 pug 中的 javascript/jQuery 脚本?
How to pass JSON data from express to a javascript/jQuery script in pug?
我正在尝试将一些 JSON 数据从快速路由传递到 .pug 模板中的 .js 文件。我不知道如何实现这一目标。我正在尝试如下:
路由器:
// Office Locations
router.get('/office_locations', (req, res, next) => {
var sql = 'SELECT * FROM office_locations ORDER BY oloffice';
var params = [];
pool.query(sql, params, (err, result) => {
if (err) {
console.log(err);
res.json(err);
} else {
res.render('office_locations', {title: title, tabledata: JSON.stringify(result.rows)});
}
});
});
PUG 文件:
extends layout
block content
.container
include menu.pug
.workspace
.map-content
.map#map
include main-addons.pug
link(rel="stylesheet" href="https://unpkg.com/leaflet@1.4.0/dist/leaflet.css" integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA==" crossorigin="")
script(src="https://unpkg.com/leaflet@1.4.0/dist/leaflet.js" integrity="sha512-QVftwZFqvtRNi0ZyCtsznlKSWOStnDORoefr1enyq5mVL4tmKB3S/EnC3rRJcxCPavG10IcrVGSmPh6Qw5lwrg==" crossorigin="")
script(src="/javascripts/office_locations.js")
script(src="/javascripts-dev/table.js")
我需要表数据信息的文件是table.js:
$(document).ready(function() {
// get the table data
var tabledata = !{tabledata};
console.log(tabledata);
});
但是在登录到控制台时我总是报错。
如何实现?
在 script(src="/javascripts-dev/table.js")
行之前添加此代码:
script(type='text/javascript').
window.tabledata = "#{tabledata}";
我正在尝试将一些 JSON 数据从快速路由传递到 .pug 模板中的 .js 文件。我不知道如何实现这一目标。我正在尝试如下:
路由器:
// Office Locations
router.get('/office_locations', (req, res, next) => {
var sql = 'SELECT * FROM office_locations ORDER BY oloffice';
var params = [];
pool.query(sql, params, (err, result) => {
if (err) {
console.log(err);
res.json(err);
} else {
res.render('office_locations', {title: title, tabledata: JSON.stringify(result.rows)});
}
});
});
PUG 文件:
extends layout
block content
.container
include menu.pug
.workspace
.map-content
.map#map
include main-addons.pug
link(rel="stylesheet" href="https://unpkg.com/leaflet@1.4.0/dist/leaflet.css" integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA==" crossorigin="")
script(src="https://unpkg.com/leaflet@1.4.0/dist/leaflet.js" integrity="sha512-QVftwZFqvtRNi0ZyCtsznlKSWOStnDORoefr1enyq5mVL4tmKB3S/EnC3rRJcxCPavG10IcrVGSmPh6Qw5lwrg==" crossorigin="")
script(src="/javascripts/office_locations.js")
script(src="/javascripts-dev/table.js")
我需要表数据信息的文件是table.js:
$(document).ready(function() {
// get the table data
var tabledata = !{tabledata};
console.log(tabledata);
});
但是在登录到控制台时我总是报错。
如何实现?
在 script(src="/javascripts-dev/table.js")
行之前添加此代码:
script(type='text/javascript').
window.tabledata = "#{tabledata}";