如何从html文件中提取文本值来表达js

编程入门 行业动态 更新时间:2024-10-05 07:26:15

如何从html文件中提取<a href=https://www.elefans.com/category/jswz/34/1771357.html style=文本值来表达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

本文发布于:2024-05-30 10:38:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1770406.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文本   文件   html   js

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!