(5). HTTP进度事件:(并非所有浏览器都支持)
可以使用是否包含属性名来判断
if ("onprogress" in (new XMLHttpRequest())) {}
a. onloadstart事件:当请求发送时触发;
b. onprogress事件:当正在加载服务器响应时,通常每隔50毫秒触发,注意如果请求完成太快,可能不会触发该事件;
事件的属性:lengthComputable表示能否获得内容长度,loaded表示已加载字节数,total表示总字节数。
request.onprogress = function(e) { if (e.lengthComputable) { progress.innerHTML = Math.round(100 * e.loaded / e.total) + "% Complete"; } };
c. onload事件:请求完成时触发;
d. ontimeout:请求超时;
调用timeout属性读写超时时间:
以下是兼容的做法:
function timedGetText(url, timeout, callback) { var request = new XMLHttpRequest(); var timer = setTimeout(function() { }, timeout); request.open("GET", url); request.onreadystatechange = function() { if (request.readyState !== 4) return; if (timedout) return; clearTimeout(timer); if (request.status === 200) callback(request.reponseText); }; request.send(null); }
e. onabort:请求终止;
可以调用xhr对象的abort方法来终止请求。
f. onerror: 请求错误;
g. upload: 上传进度对象;
whenReady(function() { var elts = document.getElementsByClassName("fileDropTarget"); for (var i = 0; i < elts.length; i++) { var target = elts[i]; var url = target.getAttribute("data-uploadto"); if (!url) continue; createFileUploadDropTarget(target, url); } function createFileUploadDropTarget(target, url) { var uploading = false; console.log(target, url); target.ondragenter = function(e) { console.log("dragenter"); if (uploading) return; var types = e.dataTransfer.types; if (types && ((types.contains && types.contains("Files")) || (types.indexOf && types.indexOf("Files") !== -1))) { target.classList.add("wantdrop"); return false; } }; target.ondragover = function(e) { if (!uploading) return false; }; target.ondragleave = function(e) { if (!uploading) target.classList.remove("wantdrop"); }; target.ondrop = function(e) { if (uploading) return false; var files = e.dataTransfer.files; if (files && files.length) { uploading = true; var message = "Uploading files:<ul>"; for (var i = 0; i < files.lenght; i++ ) message += "<li>" + files[i].name + "</li>"; message += "</ul>"; target.innerHTML = message; target.classList.remove("wantdrop"); target.classList.add("uploading"); var xhr = new XMLHttpRequest(); xhr.open("POST", url); var body = new FormData(); for (var i = 0; i < files.length; i++) body.append(i, files[i]); xhr.upload.onprogress = function(e) { if (e.lengthComputable) { target.innerHTML = message + Math.round(e.loaded / e.total * 100) + "%"; } }; xhr.upload.onload = function(e) { uploading = false; target.classList.remove("uploading"); target.innerHTML = "Drop files to upload"; }; xhr.send(body); return false; } target.classList.remove("wantdrop"); }; } });
(6). 跨域HTTP请求:
使用跨域资源共享:CORS,注意,不一定所有浏览器都支持。
判断是否支持跨域资源共享:
(new XMLHttpRequest()).withCredentials !== undefined;
判断是否是跨域链接:
link.host !== location.host || link.protocol !== location.protocol