使用jQuery Form插件上传文件时,如何提交额外数据
How can I submit additional data when uploading a file with the jQuery Form Plugin?
根据这个问题,我正在使用Malsup的jQuery Form插件异步上传文件。
它非常适合上传文件,但我有兴趣在上传文件的同时发送额外的数据(比如上传者的用户名。
有没有办法添加这些额外的数据?
以下是当前用于上传文件的代码:
(假设HTML形式的标准<input type=file/>
具有id=upload
)
// site/js/app.js
var app = app || {};
(function($){
})(jQuery);
// prepare the form when the DOM is ready
$(document).ready(function() {
var options =
{
url: 'http://localhost:3000/file_upload',
dataType: 'json',
success: function(response, statusText, xhr, form)
{
alert('success!');
};
$("#upload").ajaxForm(options);
});
玩了几天后,我找到了答案。
简单地说,有一个"数据"的"选项"属性,它包含将发送到服务器的所有内容。当使用Form设置为enctype="multipart/form-data"
时,这只获取文件类型输入,忽略其他所有内容。
但是,如果您可以访问其他输入字段的值(听起来像是$!的作业),则可以使用特定的回调函数手动添加额外的数据。
这将使您的jQuery代码看起来像这样:
// site/js/app.js
var app = app || {};
(function($){
})(jQuery);
/*
$('#upload').submit(function()
{
alert('Handler for .submit() called.');
return false;
})*/
// prepare the form when the DOM is ready
$(document).ready(function() {
var options =
{
url: 'http://localhost:3000/file_upload',
dataType: 'json',
beforeSubmit: function(arr, $form, options)
{
//add additional data that is going to be submit
//for example
arr.push({ 'name': 'username',
'value': 'Jarrod Dixon'});
},
};
$("#upload").ajaxForm(options);
});
在我的例子中,我使用express.js作为我的Web服务器,这意味着额外的数据在app.post的response的"param"属性req.param('username')
中可用。
即
app.post('/file_upload', function(req, res) {
//see if we got the username
console.log('name = '+ req.param('username'));
//Jarrod Dixon
});
希望这能帮助其他人节省数小时的搜索时间!
相关文章:
- Javascript生成的表单未提交
- 将输入字段中的文本提交到我的数据库,同时将其添加到我的列表中
- HTML表单提交时未执行外部函数
- 在POST中将html表作为csv提交
- 我应该使用Ng提交还是点击表格
- 我想使用模态通过php文件发送邮件,并且我希望在提交关闭后关闭pop
- 提交后保留下拉选择的值
- 键入最后一位数字后自动提交
- 阻止表单元素提交
- JS表单提交"无法使用Chrome数据保护程序加载此页面.尝试重新加载页面.调试信息:POST CISmtuK
- Jquery提交表单而不刷新
- 将图像上传ajax与表单提交ajax相结合
- Jquery表单验证插件-如果选中复选框,如何在提交时执行某些操作
- 自定义表单验证和提交
- 带有验证和隐藏字段值的提交按钮
- 如何在 API 调用后和 if 语句中启用提交按钮
- Jquery函数在错误的时间提交
- Ruby On Rails Ajax 提交提交两次
- Keyup 13事件重复暗示提交-提交表单上的进入问题
- 通过Enter(特定的提交提交名称)提交