如何使用response.write中的数据

时间:2019-06-12 23:03:54

标签: javascript

我正在使用以下代码打开一个html页面。我还使用response.write()函数将数据发送到该页面:

aggregate

当页面打开时,如何使用calc.html中'sum'的值?在中的script标记中,我利用Window.onload方法在页面加载时执行操作。加载时,数字9出现在网页的左上角,所以我知道它在那里,我只是不知道如何使用和使用它。

maven-site-plugin

2 个答案:

答案 0 :(得分:3)

您在此处编写的内容将作为HTML页面(在本例中)被接收,这就是为什么它仅在浏览器中显示数字“ 9”的原因。如果将其打包在<script>标记中,它将以JS形式提供:

resp.writeHead(200, {'Content-Type':'text/html'});
var sum = 9;
resp.write('<script type="text/javascript">var mySumVar = ' + sum + ';</script>');
return resp.end(data); //the "return" doesn't change anything,
                       //but it's good practice to make sure the function ends here

...然后您可以从其他客户端脚本访问mySumVar。请注意,这将在全局范围内进行,这使得更易于访问,但也有不好的做法。您可能希望将其打包在其他对象中,以避免污染范围。

答案 1 :(得分:-2)

您可以写占位符,而不是在页面顶部写数字,而这些占位符将被数据替换。例如,您可以使用{{sum}}作为占位符,并将{{sum}}替换为您的总和:

fs.readFile('./calc.html', function(error, data){
   if(error){
       //do nothing for now              
   } else if (data){
       resp.writeHead(200, {'Content-Type':'text/html'});
       var sum = 9;
       resp.end(data.replace("{{sum}}", sum);
   }
});

和您的html中。

<script type="text/javascript">
    var number = 0;
    function fetchData() {
        number = {{sum}};
    }
    window.onload = fetchData;        
</script>

如果您打算从服务器端将更多逻辑包含到网页中,建议您使用EJS之类的模板引擎。