使用express

时间:2019-02-09 18:55:08

标签: html node.js express ejs

我需要使用express获取所选对象的索引,以便在app.js中进行控制 example.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')
});

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

1 个答案:

答案 0 :(得分:0)

您应该在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