我只想将变量从HTML页面传递到节点js并对数据执行一些计算并使用ejs将其恢复为HTML 安装ejs之后:
npm install ejs
我正在尝试使用值50“HTML Page”传递此变量temp:
<html>
<head>
</head>
<body>
My temperature: <%= temp=50 %>
Temp + 10 : <%= total %>
</body>
</html>
和我的nodejs server.js:
var http = require('http');
var ejs = require('ejs');
var fs = require('fs');
http.createServer(function(req,res) {
res.writeHead(200, {'Content-Type': 'text/html'});
//since we are in a request handler function
//we're using readFile instead of readFileSync
fs.readFile('index.html', 'utf-8', function(err, content) {
if (err) {
res.end('error occurred');
return;
}
var temp; //here you assign temp variable with needed value
var total = temp+10;
var renderedHtml = ejs.render(content, {temp: temp, total:total}); //get redered HTML code
res.end(renderedHtml);
});
}).listen(8080);
任何帮助将不胜感激 提前谢谢。
答案 0 :(得分:1)
在您的服务器文件中,temp的值未定义。所以total = undefined + 10 = undefined。因此,您的变量在服务器文件中未定义。
尝试这样做(在服务器文件中):
var temp = 0
var total = 0
在html文件中My temperature: <%= temp = 50 %>
Temp + 10 : <%= total = temp + 10 %>
现在它应该显示正确的值,即50和60.希望这有帮助
答案 1 :(得分:0)
您不需要此var express = require('express');
var app = express();
var path = require('path'); //Use the path to tell where find the .ejs files
// view engine setup
app.set('views', path.join(__dirname, 'views')); // here the .ejs files is in views folders
app.set('view engine', 'ejs'); //tell the template engine
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) { // route for '/'
var temp = 50; //here you assign temp variable with needed value
var total = temp+10;
res.render('index', { //render the index.ejs
temp: temp,
total:total
});
});
var server = app.listen(3000, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
要求。
您需要做的就是:
<html>
<head>
</head>
<body>
My temperature: <%= temp %>
Temp + 10 : <%= total %>
</body>
</html>
HTML(重命名为 index.ejs ):
a