加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ajax实现进度条

发布时间:2020-12-16 02:57:27 所属栏目:百科 来源:网络整理
导读:/* *@url --string下载路径 *@filename --string文件名称 */ downLoadProcess(url,filename){filename = filename || ‘xxx.csv‘;// 创建xhr对象var req = new XMLHttpRequest(); //向服务器发送请求 open() send()req.open("POST",url,true); //(method-GE
/*
  *@url --string下载路径
  *@filename  --string文件名称
*/
downLoadProcess(url,filename){
			filename = filename || ‘xxx.csv‘;
			// 创建xhr对象
			var req = new XMLHttpRequest(); 
			//向服务器发送请求 open() send()
			req.open("POST",url,true);    //(method-GET/POST,async) 
			req.setRequestHeader("Content-type","application/x-www-form-urlencoded");//POST时需要传递			
			//监听进度事件            
			req.addEventListener("progress",function (evt) {                
				if (evt.lengthComputable) {                    
					var percentComplete = evt.loaded / evt.total;
					console.log(percentComplete);
					$("#progressing").html((percentComplete * 100) + "%");
				}
			},false);
			/*
				XMLHttpRequest 的 responseType 属性
				一个枚举类型的属性,返回响应数据的类型,只能设置异步的请求
				1、‘‘                 -- DOMString (默认);  UTF-16
				2、arraybuffer        -- arraybuffer对象,即类型化数组
				3、blob               -- Blob对象, 二进制大数据对象
				4、document           -- Document对象
				5、json
				6、text				
			*/
			//设置返回数据的类型
			req.responseType = "blob";
			
			req.onreadystatechange = function () {  //同步的请求无需onreadystatechange      
				if (req.readyState === 4 && req.status === 200) {                    
					var filename = $(that).data(‘filename‘);                    
					if (typeof window.chrome !== ‘undefined‘) {                        
						// Chrome version
						var link = document.createElement(‘a‘);
						link.href = window.URL.createObjectURL(req.response);
						link.download = filename;
						link.click();
					} else if (typeof window.navigator.msSaveBlob !== ‘undefined‘) {                        
						// IE version
						var blob = new Blob([req.response],{ type: ‘application/force-download‘ });
						window.navigator.msSaveBlob(blob,filename);
					} else {
						// Firefox version
						var file = new File([req.response],filename,{ type: ‘application/force-download‘ });
						window.open(URL.createObjectURL(file));
					}
				}
			};
			
			req.send("fname=Henry&lname=Ford");
		}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读