[英]Variables between HTML Client and Node.js Server
我只是想將變量從HTML頁面傳遞到節點js並對數據執行一些計算並使用ejs將其恢復為HTML安裝ejs之后:
npm install ejs
我試圖通過值50“HTML頁面”傳遞此變量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);
任何幫助將不勝感激提前感謝。
在您的服務器文件中,temp的值未定義。 所以total = undefined + 10 = undefined。 因此,您的變量在服務器文件中未定義。 嘗試這樣做(在服務器文件中): var temp = 0 var total = 0
在html文件中My temperature: <%= temp = 50 %> Temp + 10 : <%= total = temp + 10 %>
現在它應該顯示正確的值,即50和60.希望這有助於
你不需要這個fs
要求。
你需要做的就是:
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(重命名為index.ejs ):
<html>
<head>
</head>
<body>
My temperature: <%= temp %>
Temp + 10 : <%= total %>
</body>
</html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.