【问题标题】:how do I send my stringified object to html body如何将我的字符串化对象发送到 html 正文
【发布时间】:2020-01-29 05:25:53
【问题描述】:

我使用res.write() 方法向客户端发送html 文件。我还想发送一个object 附加到这个html。 我尝试stringify 那个对象并像我写html 文件一样写它,但是当我这样做时,我的字符串化json object 仍然在html 之外。我需要那个json对象在html里面,所以我可以用客户端js文件解析它。

我应该如何解决这个问题?

我尝试将其作为Json object 发送。但我无法通过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 文件中..

【问题讨论】:

    标签: javascript html node.js json express


    【解决方案1】:

    您可以在 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 中添加通配符,而只需用您的内容 + 结束标签本身替换您的结束标签之一,例如 &lt;\body&gt;&lt;\html&gt;...

    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();
    })
    });
    

    【讨论】:

    • 感谢您的意见。这很有意义。但是 node js 不能用 data.replace 方法编译。它需要一些 npm 吗? (TypeError:data.replace 不是函数)
    • 如果其他人遇到这个问题,上面的答案很完美。只需将 data.replace 更改为 data.toString().replace。
    【解决方案2】:

    HTML 文件:

    <html>
    
    ...
    { content }
    ...
    
    </html>
    

    你的代码:

    app.get('/uniform', (req,res) => {
      fs.readFile('uniformflowindex.html', function(err, data) {
        var channelobj = JSON.stringify(channel);
        data = data.replace('{ content }', "<div id='objectstring'>" + channelobj + "</div>");
        res.end(data);
       })
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-18
      • 2014-03-12
      • 2021-04-08
      • 1970-01-01
      • 2016-10-05
      • 2022-09-27
      • 2021-08-01
      • 1970-01-01
      相关资源
      最近更新 更多