JavaScript—异步提交表单的6种方式
FormData的详细介绍及使用请点击此处,那里对FormData的方法和事件已经表述的非常清楚,这里就不再浪费时间在介绍一遍了。本文主要针对FormData对象的使用以及异步文件上传进行详细的说明。
FormData对象可以让我们组织一个使用XMLHttpRequest对象发送的键值对的集合。它主要用于发送表单数据,但是可以独立于使用表单传输的数据。
1、从头开始创建一个FormData对象
你可以创建一个你自己的FormData对象,然后通过append() 方法向对象中添加键值对,就像下面这样:
var formData = new FormData();
formData.append("username", "Groucho");
formData.append("accountnum", 123456); // number 123456 is immediately converted to a string "123456"
// HTML file input, chosen by user
formData.append("userfile", fileInputElement.files[0]);
// JavaScript file-like object
var content = '<a id="a"><b id="b">hey!</b></a>'; // the body of the new file...
var blob = new Blob([content], { type: "text/xml"});
formData.append("webmasterfile", blob);
var request = new XMLHttpRequest();
request.open("POST", "http://foo.com/submitform.php");
request.send(formData);
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
注意:字段”userfile” 和 “webmasterfile” 都包含文件(file)。被分配到字段”accountnum”上的数字直接被FormData.append()方法转换成了字符串(字段的值(value)可能是一个Blob, File, 或一个string:如果值既不是Blob也不是File,则值会被转换成一个string)。
这个例子创建了一个FormData实例,其中包含字段”username”, “accountnum”, “userfile” 和 “webmasterfile”,然后使用XMLHttpRequest对象的send()方法去发送表单数据。字段”webmasterfile”是一个Blob。一个Blob对象代表一个文件对象的原始数据。但是Blob代表的数据不必须是javascript原生格式的数据。文件接口是基于Blob,继承Blob功能和扩大它对用户文件系统的支持。为了构建一个Blob可以调用Blob()构造函数。
2、从一个HTML表单获得一个FormData对象
为了获得一个包含已存在表单数据的FormData对象,在创建FormData对象的时候需要指定表单元素。
var formData = new FormData(someFormElement);
- 1
就像下面这样:
var formElement = document.querySelector("form");
var request = new XMLHttpRequest();
request.open("POST", "submitform.php");
request.send(new FormData(formElement));
- 1
- 2
- 3
- 4
你也可以在获得FormData对象之后增加另外的数据,就像下面这样:
var formElement = document.querySelector("form");
var formData = new FormData(formElement);
var request = new XMLHttpRequest();
request.open("POST", "submitform.php");
formData.append("serialnumber", serialNumber++);
request.send(formData);
- 1
- 2
- 3
- 4
- 5
- 6
这样你可以在发送之前增加额外的信息,不一定是用户编辑的。
3、使用FormData对象发送文件
你可以使用FormData发送文件。简单的<form>中在包含一个<input>元素就可以:
<form enctype="multipart/form-data" method="post" name="fileinfo">
<label>Your email address:</label>
<input type="email" autocomplete="on" autofocus name="userid" placeholder="email" required size="32" maxlength="64" /><br />
<label>Custom file label:</label>
<input type="text" name="filelabel" size="12" maxlength="32" /><br />
<label>File to stash:</label>
<input type="file" name="file" required />
<input type="submit" value="Stash the file!" />
</form>
<div></div>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
然后你可以使用下面的代码去发送:
var form = document.forms.namedItem("fileinfo");
form.addEventListener('submit', function(ev) {
var oOutput = document.querySelector("div"),
oData = new FormData(form);
oData.append("CustomField", "This is some extra data");
var oReq = new XMLHttpRequest();
oReq.open("POST", "stash.php", true);
oReq.onload = function(oEvent) {
if (oReq.status == 200) {
oOutput.innerHTML = "Uploaded!";
} else {
oOutput.innerHTML = "Error " + oReq.status + " occurred when trying to upload your file.<br \/>";
}
};
oReq.send(oData);
ev.preventDefault();
}, false);
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21

你也可以直接向FormData对象中添加File或Blob,就像下面这样:
data.append("myfile", myBlob, "filename.txt");
- 1
当使用append() 方法的时候,可能会使用到第三个参数去发送文件名称(通过Content-Disposition头发送到服务器)。如果没有指定第三个参数或这个参数不被支持的话,第三个参数默认是”blob”。
如果你设置好正确的options,你也可以和jQuery配合起来使用:
var fd = new FormData(document.querySelector("form"));
fd.append("CustomField", "This is some extra data");
$.ajax({
url: "stash.php",
type: "POST",
data: fd,
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
});
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
JavaScript—异步提交表单的6种方式的更多相关文章
- 使用AJAX异步提交表单的几种方式
方式一 手工收集所有的用户输入,封装为大的“k1=v1&k2=v2…”键值对形式,使用$.post(url, data,fn)把数据提交给服务器 $.ajax({ type:'post', u ...
- C# MVC提交表单的四种方式(转)
Mvc 提交表单的4种方法全程详解(转) 一,MVC HtmlHelper方法 Html.BeginForm(actionName,controllerName,method,htmlAttribu ...
- 【总结-前台发送后台接收表单】MVC提交表单的四种方式
https://www.cnblogs.com/chenwolong/p/Form.html#commentform 后台控制器接收前台表单参数三种方法: 一.普通参数 HTML标签name 和参数名 ...
- MVC中提交表单的4种方式
一,MVC HtmlHelper方法 Html.BeginForm(actionName,controllerName,method,htmlAttributes){} BeginRouteForm ...
- 使用JQuery提交表单的两种方式选择
有一个表单,如果使用JQuery提交的话,可以使用下面2中方式,但他们的区别却是根据实际需求需要进行选择的. 第一种:表单按照action路径提交后,页面会刷新. $("#id") ...
- jQuery提交表单的几种方式
方式一: $.post('../Ajax/GoodsAjax.ashx?cmd=getGsList', function (result) { var result = eval('(' + re ...
- ASP.NET MVC 网站开发总结(五)——Ajax异步提交表单之检查验证码
首先提出一个问题:在做网站开发的时候,用到了验证码来防止恶意提交表单,那么要如何实现当验证码错误时,只是刷新一下验证码,而其它填写的信息不改变? 先说一下为什么有这个需求:以提交注册信息页面为例,一般 ...
- jQuery.Form.js 异步提交表单使用总结
jQuery.Form.js 是一个用于使用jQuery异步提交表单的插件,它使用方法简单,支持同步和异步两种方式提交. 第一步:引入jQuery与jQuery.Form.js <script ...
- 使用JS对form的内容验证失败后阻止提交 &&js校验表单后提交表单的三种方法总结
1.form的两个事件 submit,提交表单,如果直接调用该函数,则直接提交表单 onSubmit,提交按钮点击时先触发,然后触发submit事件.如果不加控制的话,默认返回true,因此表单总能提 ...
随机推荐
- Lua中assert( )函数的使用
当Lua遇到不期望的情况时就会抛出错误,比如:两个非数字进行相加:调用一个非函数的变量:访问表中不存在的值等.你也可以通过调用error函数显示的抛出错误,error的参数是要抛出的错误信息. ass ...
- 007-Python函数-装饰器
函数回顾 1.函数可以当做一个参数赋值给另一个函数: def func(): print("in the func") def foo(x): x() foo(func) 输出: ...
- Ueditor设置默认字体、字号、行间距,添加字体种类(转)
Ueditor默认字体.字号.行间距的修改: ueditor默认字号是16号,默认字体为sans-serif,默认行间距为5px,如下图所示: 首先,修改ueditor.all.js文件中如上图红框中 ...
- SpringBoot学习(3)-SpringBoot添加支持CORS跨域访问
SpringBoot学习(3)-SpringBoot添加支持CORS跨域访问 https://blog.csdn.net/yft_android/article/details/80307672
- asp.net Web API 身份验证 不记名令牌验证 Bearer Token Authentication 简单实现
1. Startup.Auth.cs文件 添加属性 1 public static OAuthBearerAuthenticationOptions OAuthBearerOptions { get; ...
- 本地化KendoUI
<!doctype html> <html> <head> <title>Kendo UI Web</title> ...
- 【转】ArcGIS10的附件功能
转自:http://blog.csdn.net/linghe301/article/details/6386176 老是忘记怎么使用这个ArcGIS10的附件功能,这次就做个记录吧. 在项目应用过程中 ...
- Codeforces 609F Frogs and mosquitoes 线段树
Frogs and mosquitoes 用线段树维护每个点覆盖的最小id, 用multiset维护没有吃的蚊子. #include<bits/stdc++.h> #define LL l ...
- Docker 启动tomcat
docker run -d --name jinrong_beijingbank -p 8081:8081 -v /application/docker_hub/java/pypaltform2018 ...
- python--smtp邮件使用
#构建对象时,第一个是邮件正文,第二个发送类型,plain表示纯文本,最后使用utf-8保证多语言兼容 #如果需要发送html的话,就把plain改为html------>内容使用html构造便 ...