通过html5中对于ajax的学习,我写了关于无刷新上传的代码(非原创),该代码摒弃了以前的习惯写法,即onreadystatechangge,而是 采用了onload的写法
过去实现ajax传输分为
1.获取xmlhttpquest对象 ,createXmlHttpRequest为兼容了ie和其他浏览器封装好的函数
2.检测xmlhttpquest对象状态 xhr.readyState==4&&xhr.status==200
3.发送请求xhr.send()
window.οnlοad=init(); function init(){ getData() } function getData(){ var xhr=createXmlHttpRequest(); xhr.open("Post","Area.txt",true); xhr.onreadystatechange=function(){ if(xhr.readyState==4&&xhr.status==200){ var jsonData=xhr.responseText; } xhr.send(); } } function createXmlHttpRequest(){ if(window.XMLHttpRequest){ return new XMLHttpRequest(); }else if(window.ActiveXObject){ return new ActiveXObject("Microsoft.xmlHttp") }else{ return null; } }而在html5的上传文件的过程中
var oMyFile=document.getElementById("myFile"); var oBtn=document.getElementById("btn"); oBtn.οnclick= function () { var xhr=new XMLHttpRequest(); xhr.onload=function(){ //监听上传的事件,当后端返回处理的事件 alert("上传成功") }; var oUpload=xhr.upload; //监控上传进度事件 oUpload.onprogress=function(ev){ console.log(ev.total+':'+ev.loaded); }; xhr.open('post','post.php',true); xhr.setRequestHeader('X-Request-With','XMLHttpRequest'); //将文件转换为二进制data var oFormData=new FormData(); oFormData.append('file',oMyFile.files[0]); xhr.send(oFormData) };