【问题标题】:Get the index of selected option in node.js with using express使用 express 获取 node.js 中选定选项的索引
【发布时间】:2019-07-03 17:02:43
【问题描述】:

我需要使用 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')
});

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

【问题讨论】:

  • 您收到什么错误信息?
  • 我没有收到错误信息但收到的是值而不是索引
  • @shiva 你能解释一下为什么需要索引吗?
  • @Staxaaaa 我需要其他项目中的索引才能使用它从 mysql 数据库接收数据

标签: html node.js express ejs


【解决方案1】:

您应该在&lt;option&gt; 标签上寻找selected 属性。 &lt;option&gt; 标签也不支持属性 attribute。 您无法从 &lt;select&gt; 标记中获取索引。您应该为此&lt;select&gt; 创建一个包含索引和值的哈希表。然后,当您将获取该值时,请从哈希表中获取该值的索引。 类似的东西。举个例子。

<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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-28
    • 1970-01-01
    • 1970-01-01
    • 2012-11-13
    • 1970-01-01
    • 1970-01-01
    • 2018-06-13
    相关资源
    最近更新 更多