文本值来表达js"/>
如何从html文件中提取文本值来表达js
我只是想从 html 文本字段中获取值并将值分配给变量。
我需要 html 来获取所有这些值并在 .html 文件中的某处发回响应。
html:
<body>
<form>
<label for="stageURL">Stage URL:</label><br>
<input type="text" id="stageURL" name="stageURL"><br>
<label for="prodURL">Production URL:</label><br>
<input type="text" id="prodURL" name="prodURL">
</form>
<button type="submit" form="form1" value="Submit">Submit</button>
</body>
Express.js
const express = require('express');
const app = express();
const path = require('path');
const router = express.Router();
const port = 3000;
router.get('/',function(req,res){
res.sendFile(path.join(__dirname+'/index.html')); // The user will see the html file in this path.
let stageUrl = req.query.stageURL; //Need to fetch the input field data.
let prodUrl = req.query.prodURL; // Need to fetch input field data.
res.send(stageUrl+" : "+prodUrl); //print it back somewhere in the html file.
});
html视图:
我想在用户尝试访问 http://localhost:3000 时显示上面的 html 页面 当用户单击提交按钮时,我只需要获取阶段和产品 url。
回答如下:你需要的是像ejs这样的模板引擎。首先使用以下命令安装 ejs:
npm install ejs
然后你可以在你的Express服务器中设置它:
const express = require('express');
const app = express();
const path = require('path');
const router = express.Router();
const port = 3000;
app.set('view engine', 'ejs');
router.get('/', function (req, res) {
// The `index` here refers to the file in `views/index.ejs`
res.render('index', {
stageURL: req.query.stageURL || '',
prodURL: req.query.prodURL || ''
});
});
在那之后,您的
index.html
应该重命名为views/index.ejs
:
<body>
<form>
<label for="stageURL">Stage URL:</label><br />
<input
type="text"
id="stageURL"
name="stageURL"
value="<%= stageURL %>"
/><br />
<label for="prodURL">Production URL:</label><br />
<input type="text" id="prodURL" name="prodURL" value="<%= prodURL %>" />
</form>
<button type="submit" form="form1" value="Submit">Submit</button>
</body>
有关如何使用EJS的更多信息,您可以参考这里的指南:
- https://blog.logrocket/how-to-use-ejs-template-node-js-application/
- https://ejs.co/
更多推荐
如何从html文件中提取文本值来表达js
发布评论