html - 使用express获取node.js中所选选项的索引

标签 html node.js express ejs

我需要使用express获取所选对象的索引以在app.js中对其进行控制台 示例.html

<form id="tableForm" action="getJson">
        <select class="example" name="example">
              <option name="table1" value="1">Table 1</option>
              <option name="table2" value="2">Table 2</option>
              <option name="table3" value="3">Table 3</option>
        </select>
    </form>

App.js

var express = require('express'),
app = express();

app.use(express.bodyParser());

 app.get('/', function(req, res){
  res.sendfile('views/index.html');
});

app.post('/getJson', function (req, res) {
   console.log(req.body.example);
});

app.listen(3000, function(){
    console.log('Server running at port 3000: http://127.0.0.1:3000')
});

这将输出所选选项的值而不是索引。

最佳答案

您应该寻找selected属性 <option>标签。还有属性attribute <option> 不支持标签。 您无法从 <select> 获取索引标签。您应该创建一个包含此 <select> 的索引和值的哈希表。 。然后,当您获取该值时,从哈希表中获取该值的索引。 类似的事情。仅举个例子。

<form id="tableForm" action="getJson">
    <select class="example" name="example">
          <option value="Berlin">Berlin</option>
          <option value="Moscow">Moscow</option>
          <option value="Kyiv">Kyiv</option>
    </select>
</form>

const selectHashtable = {
    'Berlin': 1,
    'Moscow': 2,
    'Kyiv': 3
};

// for example req.body.example = 'Kyiv';
// you call 
selectHashtable[req.body.example]; // console.log => 3

关于html - 使用express获取node.js中所选选项的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54609599/

相关文章:

javascript - 如何防止 iFrame 在按下后退按钮时自动播放?

javascript - 身份验证 ExpressJS -> PassportJs : Error: Can't set headers after they are sent

javascript - 如何在 Node.js 中创建 Get 请求以从 json 获取特定对象?

javascript - HTML 标题工具提示在空格后被 chop

html - 使用 Angular 4 渲染 blob 图像

html - 小屏幕上的 CSS 宽度奇怪行为

javascript - Node.js 弃用对象键

sql - Node.js PostgreSQL

node.js - MongoDB auto_reconnect 不起作用

javascript - async.each 与 async.every 之间的区别?