我需要使用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/