html - 如何将数据从节点 js 传递到 html?
问题描述
如何将数据从 node.js 传递到 html 页面?我知道有模板引擎,但它们与 express 一起使用——我在本机 nodejs 中需要它。试图这样做:
let str = ''
Post.find({}, function(err, docs) {
if (err) return console.log(err)
for (let i in docs) {
str += '<tr><td>' + docs[i].title + '</td><td>' + docs[i].text + '</td></tr>'
}
});
但是如何将此变量传递str
到 html 文件中的正确位置?有这样的东西:
<div class="posts">
<table>
str
</table>
</div>
解决方案
您必须创建唯一的字符串,例如#str#
,读取文件然后替换该字符串
let str = ''
Post.find({}, function(err, docs) {
if (err) return console.log(err)
for (let i in docs) {
str += '<tr><td>' + docs[i].title + '</td><td>' + docs[i].text + '</td></tr>'
}
/*
<div class="posts">
<table>
#str#
</table>
</div>
*/
let template = fs.readFileSync('template.html');
template = template.replace('#str#', str);
});
或使用cheerio html 解析器
// template.html without "str"
/*
<div class="posts">
<table>
</table>
</div>
*/
let template = fs.readFileSync('template.html');
const cheerio = require('cheerio');
const $ = cheerio.load(template);
$('.posts table').html(str);
推荐阅读
- flutter - Flutter 创建垂直日历
- django - django 将搜索词从帖子字段传递到 URL
- python - 使用陀螺仪和加速度计数据旋转立方体
- python - 使用 Windows PowerShell 命令时使用 Python 在 VSCode 中出现编解码器错误
- serilog - Serilog sql server sink 不写消息
- javascript - 无法映射在反应 js 中收到的响应
- sql - 如何在 SQL Server 2012 中将十进制编码的十六进制转换为 ascii
- javascript - 如何承诺我的 S3 getObjectUrl 函数?
- c# - 如何在 UWP 桌面应用程序中使用 oauth2 授权代码授予流程登录
- c++ - 是否可以从 C++20 中的视图构造一个`std::span`?