我正在打开一个带有以下代码的html页面。 我还使用 response.write(( 函数将数据发送到该页面:
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.write(sum);
resp.end(data);
}
});
当页面打开时,如何在 calc 中使用 "sum.html 中的值? 在 中的脚本标记中,我正在使用 Window.onload 方法在页面加载时执行操作。 数字 9 在加载时出现在网页的左上角,所以我知道它在那里,我只是不知道如何使用它和使用它。
<script type="text/javascript">
var htmlSum = 0;
function fetchData() {
htmlSum = //How to I scrape the 'sum' variable sent into the page?????
}
window.onload = fetchData;
</script>
您在此处编写的内容将作为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
。 请注意,这将在全局范围内进行,这使得它更容易访问,但也是不好的做法。 您可能希望将其打包到其他对象中,以避免污染范围。
您可以编写将替换为数据的占位符,而不是在页面顶部写入数字。例如,您可以使用{{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。