Why input type=file not working with $.ajax?(为什么输入 type=file 不能与 $.ajax 一起使用?)
问题描述
我在表单中有一个 <s:file>
标签,它生成一个 HTML <input type="file">
.当我通过表单提交(例如提交按钮等)提交表单时,动作方法中的一切正常.但是,当我将代码更改为:
I have a <s:file>
tag inside the form which generates a HTML <input type="file">
. When I submit the form via form submission (e.g. submit button, etc.) everything works fine in the action method. However, when I change my code to:
$.ajax({
url: "actionClass!actionMethodA.action",
type: "POST",
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert('Error ' + textStatus);
alert(errorThrown);
alert(XMLHttpRequest.responseText);
},
data: $(form).serialize(),
success: function(data) {
...
}
});
在后端,file
字段总是null
.
file 字段在 action 类中定义如下(带有 setter 和 getter):
The file field is defined in the action class as follow (with setter and getter):
private File impFileUrl;
是不是因为现在表单被序列化了,导致后端不能再正确设置文件字段?
Is it because now the form is serialized so that the file field can no longer be set properly in the backend?
推荐答案
这是因为 jQuery.serialize() 只序列化输入元素,而不是其中的数据.
It is because jQuery.serialize() serializes only input elements, not the data in them.
只有成功的控件"被序列化为字符串.不提交按钮值被序列化,因为表单不是使用按钮.对于要包含在序列化的表单元素的值字符串,元素必须有一个名称属性.复选框的值和单选按钮(单选"或复选框"类型的输入)包括在内仅当它们被检查时.来自文件选择元素的数据不是序列化.
Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button. For a form element's value to be included in the serialized string, the element must have a name attribute. Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked. Data from file select elements is not serialized.
但这并不意味着你不能用ajax上传文件.可能会使用其他功能或插件来发送 FormData
对象.
But it doesn't mean that you can't upload files with ajax. Additional features or plugins might be used to send FormData
object.
如果您设置了正确的选项,您也可以将 FormData
与 jQuery 一起使用:
You can also use
FormData
with jQuery if you set the right options:
var fd = new FormData(document.querySelector("form"));
fd.append("CustomField", "This is some extra data");
$.ajax({
url: "actionClass!actionMethodA.action",
type: "POST",
data: fd,
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
});
这篇关于为什么输入 type=file 不能与 $.ajax 一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么输入 type=file 不能与 $.ajax 一起使用?
基础教程推荐
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01