我使用 res.write()
方法向客户端发送一个 html
文件。我还想发送附加到此 html
的 object
。
我尝试对该对象进行 stringify
并像编写 html
文件一样编写它,但是当我这样做时,我的 stringified json object
仍然在html
。我需要将该 json 对象放在 html
中,以便我可以使用客户端 js 文件对其进行解析。
我该如何解决?
我尝试将其作为 Json 对象
发送。但我无法通过 html
获取它。
app.get('/uniform', (req,res) => {
fs.readFile('uniformflowindex.html', function(err, data) {
var channelobj = JSON.stringify(channel);
res.write(data);
res.write("<div id='objectstring'>" + channelobj + "</div>");
res.end('');
});
});
它给出了输出:
<html>
...
my html file
...
</html>
<div id='objectstring'>{"_events":{},"_eventsCount":0,"Discharge":20,"FlowDepth":5.......}</div>
我只是想让这个 div
放在 html
文件中..
最佳答案
您可以在 html 代码中使用通配符,然后将通配符替换为您的 div 内容。
例如:
<html>
...
my html file
...
[[wildcard]]
</html>
然后使用:
app.get('/uniform', (req,res) => {
fs.readFile('uniformflowindex.html', function(err, data) {
var channelobj = JSON.stringify(channel);
res.write(data.replace('[[wildcard]]', "<div id='objectstring'>" + channelobj + "</div>"));
res.end();
})
});
或者可以不在您的 html 中添加通配符,只需替换您的结束标记之一,例如 <\body>
或 <\html>
使用您的内容 + 结束标记本身...
app.get('/uniform', (req,res) => {
fs.readFile('uniformflowindex.html', function(err, data) {
var channelobj = JSON.stringify(channel);
res.write(data.replace('</body>', "<div id='objectstring'>" + channelobj + "</div></body>"));
res.end();
})
});
关于javascript - 如何将我的字符串化对象发送到 html 正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58159048/