0
我想從我的HTML頁面發送一個簡單的表單到我的節點JS服務器。問題是:我有一個需要由用戶增加的字段,所以我使用數組來表示它。一切正常,但數組字段在服務器上的JSON對象內顯示爲一個字符串。發送HTML和節點JS之間的數組字段
下面是來自服務器的輸出:
{
nomeEquipe: 'Team',
nomeLider: 'Team Lider',
emailEquipe: '[email protected]',
matriculaLider: '10101010',
senhaLider: '001001001',
'part[0].nome': 'Partner',
'part[0].matricula': '666',
'part[0].email': '[email protected]'
}
我無法訪問部分陣列。該部分陣列可以incresed ...
index.ejs(形式和腳本):
<form method="post" action="/cadastrar">
<input type="text" name="nomeEquipe" placeholder="Nome da Equipe"><br>
<input type="text" name="nomeLider" placeholder="Lider da Equipe"><br>
<input type="email" name="emailEquipe" placeholder="Email do Lider"><br>
<input type="number" name="matriculaLider" placeholder="Matricula do Lider"><br>
<input type="password" name="senhaLider" placeholder="Senha de Login"><br><br>
<input type="text" name="part[0].nome" placeholder="Nome do participante">
<input type="number" name="part[0].matricula" placeholder="Matricula do participante">
<input type="email" name="part[0].email" placeholder="Email do participante">
<div id="participante"></div>
<br>
<button type="button" onclick="addParticipante()">Adicionar</button>
<button type="button" onclick="delParticipante()">Remover</button>
<br><br>
<button type="submit">Cadastrar</button>
</form>
<script>
var cont = 1;
function addParticipante() {
var div = document.createElement('div');
div.className = 'participante';
div.innerHTML = '<input type="text" name="part['+cont+'].nome" placeholder="Nome do participante"><input type="number" name="part['+cont+'].matricula" placeholder="Matricula do participante"><input type="email" name="part['+cont+'].email" placeholder="Email do participante">';
document.getElementById('participante').appendChild(div);
cont++
}
function delParticipante() {
var select = document.getElementById('participante');
document.getElementById('participante').removeChild(select.lastChild);
cont--
}
</script>
服務器端(路線):
var express = require('express');
var router = express.Router();
var equipe = require('./../models/Equipe')();
router.get('/', function(req, res, next) {
res.render('index', { title: 'Gincana' });
});
router.get('/cadastrar', (req, res, next) => {
equipe.find({}, (err, models) => {
if(err) console.log(err)
else res.json(models)
});
});
router.post('/cadastrar', validador, (req, res, next) => {
var model = req.body;
res.send(model);
});
function validador(req, res, next) {
var model = req.body;
console.log(model);
next()
}
module.exports = router;
非常感謝!
我仍然得到錯誤。單引號仍然存在。我無法訪問我的服務器中的對象'model.part'。我只收到'undefined'。 –
打印出模型時,您會看到「零件」? – Justinas
是的。在'model = req.body'的情況下。像我的文章中的輸出例子。現在''part [0] [nome]':'PAULO H T GLINSKI''。我可以訪問其他對象。 –