输入类型=文件不能与$ .ajax一起使用? [英] input type=file not working with $.ajax?

查看:78
本文介绍了输入类型=文件不能与$ .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.

在操作类中定义文件字段的方式如下(使用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.

只有成功的控件"才被序列化为字符串.没有提交 按钮值已序列化,因为未使用表单提交表单 按钮.对于要包含在序列化中的表单元素的值 字符串,该元素必须具有name属性.复选框中的值 和单选按钮("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
});

这篇关于输入类型=文件不能与$ .ajax一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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