简体   繁体   中英

Give value from node.js to its server's html

I need to give var into my html like server -> client
I'm not good at english and this situation is hard to explain so i will show you the code
html (index.html):

<script type="text/javascript">
console.log(tmp) //lol!
</script>

node.js:

fs.readFile('./index.html', (err, html) => {
        if (err) {
                response.statusCode = 404;
                response.end(`error!`);
        } 
        else
        {
            tmp="lol!"
            response.write(html);
            response.end(); 
        }
    });

server should response and give value to client same time. but it didn't work.
i don't want use external modules like express.js or ajax anything need to download things as it's possible
could you help me?

fs.readFile('./index.html', (err, html) => {
        if (err) {
        } 
        else
        {
            var tmp = new Object();
            tmp.string = "hello world!"
            var go = JSON.stringify(tmp)
            res.write(`<div id="data"><div id="list" data-list='${go}'></div></div>`);
            res.write(html);
            res.end(); 
        }
    });

HTML:

var data = JSON.parse(document.getElementById("list").getAttribute("data-list"));
alert(data.string);

make a div element and set attribute, then write in response.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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