为什么 input type=file 不适用于 $.ajax? [英] Why input type=file not working with $.ajax?

查看:35
本文介绍了为什么 input type=file 不适用于 $.ajax?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在表单中有一个 标签,它生成一个 HTML .当我通过表单提交(例如提交按钮等)提交表单时,在 action 方法中一切正常.但是,当我将代码更改为:

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.

文件字段在action类中定义如下(使用setter和getter):

The file field is defined in the action class as follow (with setter and getter):

private File impFileUrl;

是不是因为现在表单被序列化了,不能再在后台正确设置file字段了?

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.

只有成功控制"被序列化为字符串.没有提交按钮值被序列化,因为表单没有使用按钮.对于要包含在序列化中的表单元素的值字符串,元素必须有一个名称属性.复选框中的值包括单选按钮(radio"或checkbox"类型的输入)只有当他们被检查.来自文件选择元素的数据不是序列化.

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
});

这篇关于为什么 input type=file 不适用于 $.ajax?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆