ajax是: Ajax 即“Asynchronous Javascript And XML”(異步 JavaScript 和 XML)
基本使用
let hxr =new XMLHttpRequest();
xhr.open("get",url,true); //true是異步,false是同步
xhr.onload=function(){
let res=JSON.parse(xhr.responseText);
}
xhr.send();
get 和past
- get注意點(diǎn)
- get通過(guò)parmas傳參
- get和querystring的問(wèn)題,通過(guò)url傳參
- post注意點(diǎn)
- 發(fā)送數(shù)據(jù)時(shí)候需要設(shè)置http正文頭格式;
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); //默認(rèn)編碼
xhr.setRequestHeader("Content-type","mulitipart/form-data");//二進(jìn)制編碼
xhr.setRequestHeader("Content-type","application/json"); //json編碼
- 獲取頭部信息菱父;
getAllResponseHeaders 或者是getResponseHeader 撇簿;
onreadystatechange
onreadystatechange:存有處理服務(wù)器響應(yīng)的函數(shù),每當(dāng) readyState 改變時(shí)齐板,onreadystatechange 函數(shù)就會(huì)被執(zhí)行张吉。
readyState:存有服務(wù)器響應(yīng)的狀態(tài)信息霞势。
- 0: 請(qǐng)求未初始化(代理被創(chuàng)建,但尚未調(diào)用 open() 方法)
- 1: 服務(wù)器連接已建立(
open
方法已經(jīng)被調(diào)用) - 2: 請(qǐng)求已接收(
send
方法已經(jīng)被調(diào)用泞坦,并且頭部和狀態(tài)已經(jīng)可獲得) - 3: 請(qǐng)求處理中(下載中窖贤,
responseText
屬性已經(jīng)包含部分?jǐn)?shù)據(jù)) - 4: 請(qǐng)求已完成,且響應(yīng)已就緒(下載操作已完成)
利用FormData來(lái)實(shí)現(xiàn)文件上傳
- 監(jiān)控上傳進(jìn)度
upload 事件
- onloadstart 上傳開(kāi)始
- onprogress 數(shù)據(jù)傳輸進(jìn)行中
- evt.total :需要傳輸?shù)目偞笮贰锁。?/li>
- evt.loaded :當(dāng)前上傳的文件大性呶唷;
- onabort 上傳操作終止
- onerror 上傳失敗
- onload 上傳成功
- onloadend 上傳完成(不論成功與否)
//html
<input type="file" class="myfile" /> //multiple允許選擇多個(gè)文件
進(jìn)度:<progress value="0" max="100"></progress> <span class="percent">0%</span>
<br/>
速度:<span class="speed">20b/s</span>
<button>點(diǎn)擊上傳</button>
<button>取消上傳</button>
//javascript
let xhr = new XMLHttpRequest();
let btns = document.querySelectorAll("button");
let sTime;
let sloaded;
btn[0].onclick = function () {
let file = document.querySelector(".myfile").files[0];
let form = new FormData();
form.append("myfile", file);
xhr.open("post", url, true);
xhr.upload.onloadstart = function () {
console.log("開(kāi)始上傳");
sTime = new Date().getTime();
sloaded = 0;
}
xhr.upload.onprogress = function (evt) {
let endTime = new Date().getTime();
let dTime = (endTime - sTime) / 1000; // 時(shí)間差豌熄;
let dloaded = ent.loaded - sloaded; // 當(dāng)前時(shí)間內(nèi)上傳的文件大小
let speed = dloaded / dTime;
let unit = "b/s";
stime = new Date().getTime();
sloaded = ent.loaded;
if (speed / 1024 > 1) {
unit = "kb/s";
speed = speed / 1024;
}
if (speed / 1024 > 1) {
unit = "mb/s";
speed = speed / 1024;
}
let percent = (evt.loaded / evt.total * 100).toFixed(0);
// console.log(percent);
document.querySelector("progress").value = percent;
document.querySelector(".percent").innerHTML = percent + "%";
}
xhr.upload.onload = function () {
console.log("上傳成功");
}
xhr.upload.onloadend = function () {
console.log("上傳完成"); //
}
xhr.upload.onabort = function () {
console.log("取消上傳");
}
xhr.send(form);
}
btns[1].onclick = function () {
xhr.abort();
}