Ajax进阶 FormData对象

  Ajax基础:http://www.cnblogs.com/-beyond/p/7919369.html

xhr 2.0及FormData介绍

  FormData对象 其实和 XMLHttpRequest对象 是一样的,和Date,Array这些对象也是一样的,都是window对象的属性。

  前面那个链接中内容全是XMLHttpRequest 1.0版本。。但是既然ajax这么好用,自然就要扩展了,做了点升级,于是就有了XMLHttpRequest 2.0,人称XMLHttpRequest 2级。

  想想如果使用post方式请求数据的时候,同时又提交了一些数据,于是就要设置一些Content-Type为x-www-form-urlencoded头部信息,否则后端程序收到之后,不能通过$_POST来获取(针对PHP),

  而且如果想要使用ajax来发送文件,那么,困难还是有的。

  所以呢,XMLHttpRequest 2.0版本中就增加一个狠角色——FormData对象 ,为什么说他狠呢,因为,可以把一个实例化的FormData对象直接作为xhr.send的参数,而不需要设置头部信息。同时支持发送文件,其实都没啥的。对于FormData来说也就是小case。

  

FormData属性及方法

  可以通过console.log(window)来找到FormData对象,看一看他的属性和方法

  方法:见名知意

  set("key","value")

  append("key","value")

  delete("key")   

  get("key")

  getAll("key")   

 

使用FormData

  下面是FormData的使用示例:

var fd = new FormData();

//set会覆盖,简记为设置单一变量
fd.set("name","test");
fd.set("name","demo");
console.log(fd.get("name")); //demo
console.log(fd.getAll("name")); //["demo"]

//append会创建一个数组,key就是数组名
fd.append("name","abc");
fd.append("name","xyz");
console.log(fd.get("name")); //abc
console.log(fd.getAll("name"));//["abc", "xyz"]

//删除key的值
fd.delete("name");
console.log(fd.get("name")); //null

  

FormData搭配XMLhttpRequest

  就如开头所说的,FormData对象直接作为xhr.send的参数,即可发送数据,前提是不是get方法,可以是post方法(通常都是)。

var xhr = new XMLHttpRequest();
var fd = new FormData();
fd.append("name[]","demo");
fd.append("name[]","test");
//注意要传递数组的话,一定要在key后面加一个[],否则服务器只能收到最后一次append的值
xhr.open("post","recieve.php",true);
xhr.send(fd);
xhr.onreadystatechange = function(){
	if(xhr.readyState==4){
		if((xhr.status==200 && xhr.status<300) || xhr.status==304){
			console.log(xhr.responseText);
		} else {
			console.log("请求失败,响应码:" + xhr.status)
		}
	}
}

  

  

  

原文地址:https://www.cnblogs.com/-beyond/p/7919703.html