javascript 表单提交/节点后防止页面重新加载(没有可用的ajax)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22163220/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Prevent page reload after form submit / node (no ajax available)
提问by Serg Nights
Good day, I have a form for sending fields and fileto node.js server. On server the data parsed by Formidable. Everything is working good, but after form submitted it loads a page with a response. Does anyone know either the way to send the data with standard form mechanisms andnot reload page (jQuery ajax method with serialize will not work because of file in form) either write such response on server so it will not trigger page reload. Form:
美好的一天,我有一个用于将字段和文件发送到 node.js 服务器的表单。在服务器上由Formidable解析的数据。一切正常,但在提交表单后,它会加载一个带有响应的页面。没有人知道或者发送与标准形式机制数据的方式,并不会重新加载页面(jQuery的AJAX方法与连载不会因为工作中的表单文件)无论是写在服务器,因此不会触发页面重载这样的响应。形式:
<form action="/upload" enctype="multipart/form-data" method="post" id="eventForm">
<label>Date</label>
<input type="text" name="date"/>
<label>Image</label>
<input type="file" multiple="multiple" name="picture" />
<input type="submit" value="Submit!" />
</form>
Server side:
服务器端:
app.post('/upload', function (req, res) {
var form = new formidable.IncomingForm();
// save file code goes here
form.parse(req, function(err, fields, files) {
//response code goes here
res.send('done');
});
});
Any better ways to do this? Thank you!
有没有更好的方法来做到这一点?谢谢!
回答by Serg Nights
Thanks to both of people who answered in comments to my question! Both of their solutions are working and here they are:
感谢两位在评论中回答我的问题的人!他们的两种解决方案都在起作用,它们是:
1) Easiest: add invisible iframe after the form and specify it as a target of a form:
1) 最简单:在表单后添加不可见的 iframe 并将其指定为表单的目标:
<form action="/upload" enctype="multipart/form-data" method="post" id="eventForm" target="uploader_iframe">
//....
</form>
<iframe id="uploader_iframe" name="uploader_iframe" style="display: none;"></iframe>
2) Correct: actually it is not that hard to use AJAX to send the same data, you just need to specify some parameters to make it work right. Here is a code:
2) 正确:其实用 AJAX 发送同样的数据并没有那么难,你只需要指定一些参数就可以让它正常工作。这是一个代码:
$('#eventForm').submit(function (e) {
e.preventDefault();
var fd = new FormData($(this)[0]);
$.ajax({
url: '/upload',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
console.log(data);
}
});
});
Thank you both commentators! Use their links to find more about it!
谢谢两位解说!使用他们的链接找到更多相关信息!