问题
I've a <form>
to upload an image and a <fieldset>
to send some data using AJAX, they both work fine, but my problem happens when I try to merge them in one form. I'm using Node.JS server.
Upload <form>
:
<form method="post" enctype="multipart/form-data" action="upload">
<input type="file" name="upl"/>
<input type="submit" value="Send"/>
</form>
Node.JS router upload post:
router.post('/upload', upload, function (req, res, next) {
console.log(req.file);
res.status(204).end();
});
<fieldset>
:
<div id="addAdv">
<fieldset class="form-group">
<label for="inputTimeStamp">Time</label>
<input id="inputTimeStamp" type="text" class="form-control"/><br/>
<label for="inputURL">URL</label>
<input id="inputURL" type="url"/><br/>
<button id="btnAddAdv" type="submit" class="btn btn-primary">Submit</button>
</fieldset>
</div>
Node.Js router data post:
router.post('/addadv', function(req, res) {
Feed.collection.insert(req.body, function(err, result){
res.send(
(err === null) ? { msg: '' } : { msg: err }
);
});
});
AJAX:
$('#btnAddAdv').on('click', addAdv);
function addAdv(event) {
.....
$.ajax({
type: 'POST',
data: newUser,
url: '/addadv',
dataType: 'JSON'
}).done(function( response )...}
Let's try to merge them:
<div id="addAdv">
<form method="post" enctype="multipart/form-data" action="upload">
<fieldset class="form-group">
<input type="file" name="upl"/>
<label for="inputTimeStamp">Time</label>
<input id="inputTimeStamp" type="text" class="form-control"/><br/>
<label for="inputURL">URL</label>
<input id="inputURL" type="url"/><br/>
<input type="submit" id="btnAddAdv" value="Send"/>
</fieldset>
</form>
</div>
Also tried:
<button id="btnAddAdv" type="submit">Send</button>
回答1:
If you're submitting your merged form via the submit button and not via XHR, then you need to add name
attributes for your non-file fields, otherwise the browser will not send them to the server.
来源:https://stackoverflow.com/questions/36022894/merging-form-and-fieldset-doesnt-work