AJAX是什么
AJAX = Async JavaScript And XML
可以說用JS發(fā)請求和收響應(yīng)就是AJAX的全部內(nèi)容
AJAX是瀏覽器上的功能
- 瀏覽器可以發(fā)請求,收響應(yīng)
- 瀏覽器在window上加了一個XMLHttpRequest函數(shù)
- 用這個構(gòu)造函數(shù)(類)可以構(gòu)造出一個對象
JS通過它來發(fā)請求和收響應(yīng)
利用AJAX來加載CSS寻拂、JS布近、HTML佳镜、XML、JSON
加載CSS
我們在加載CSS一般的方法為<link rel=stylesheet href="1.css"/>
,我們也可以使用AJAX來進(jìn)行加載嫉柴。
步驟如下:
創(chuàng)建 HttpRequest 對象(全稱是 XMLHttpRequest)
調(diào)用對象的 open 方法
監(jiān)聽對象的 onload & onerror 事件
調(diào)用對象的 send 方法(發(fā)送請求)
代碼演示:
getCSS.onclick = () => {
const request = new XMLHttpRequest(); //創(chuàng)建HttpRequest對象
request.open("GET", "/style.css"); //調(diào)用對象的open方法
request.onload = () => {
console.log(request.response);
console.log("成功了");
const style = document.createElement("style"); //創(chuàng)建style標(biāo)簽
style.innerHTML = request.response; //填寫style內(nèi)容
document.head.appendChild(style); //插入到head標(biāo)簽里面
}; //監(jiān)聽對象的onload事件
request.onerror = () => {
console.log("失敗了");
}; //監(jiān)聽對象的error事件
request.send(); //調(diào)用對象的send方法
};
加載JS
我們以前使用常規(guī)方法就是引入<script src="2.js"></script>
胖眷,JS也是可以用AJAX來進(jìn)行實現(xiàn)的武通。
步驟同CSS就不進(jìn)行演示了。
加載HTML
以往我們在一個html中是不會加載一個html的珊搀,如果加載也是iframe標(biāo)簽冶忱。我們可以通過AJAX來對一個HTML進(jìn)行一個輕量級的請求。
步驟大致與加載CSS相同境析,具體代碼如下
getHTML.onclick = () => {
const request = new XMLHttpRequest(); //還是創(chuàng)建HTTPRequest對象
request.open("GET", "/3.html"); //調(diào)用open
request.onload = () => {
const div = document.createElement("div"); //創(chuàng)建一個div
div.innerHTML = request.response; //在這個div里面寫上內(nèi)容
document.body.appendChild(div); //放入body里面囚枪,以上三行是對于成功請求的事件進(jìn)行能夠加載的處理(輕量級請求)
};
request.onerror = () => {}; //onerror不是很好的適配AJAX
request.send();
};
onreadystatechange
可以看到以上兩段代碼都出現(xiàn)了onload和onerror,但是onerror也不會寫什么內(nèi)容劳淆。我們可以用一個更高級的API叫做onreadystatechange()
其中涉及到一個屬性叫做readystate
链沼,它是用來表示這個XMLHttpRequest對象的一生的
const request = new XMLHttpRequest(); //此時readyState=0
request.open(); //此時readyState=1
request.send(); //此時readyState=2
//響應(yīng)出第一個字節(jié)此時readyState=3
//完全下載完畢此時readyState=4
我們可以利用onreadystatechange()
來對加載CSS進(jìn)行改寫
getCSS.onclick = () => {
const request = new XMLHttpRequest(); //創(chuàng)建HttpRequest對象,此時readystate是0
request.open("GET", "/style.css"); //調(diào)用對象的open方法,此時readystate是1
request.onreadystatechange = () => {
console.log(request.readyState);
if (request.readyState === 4) {
//下載完成憔儿,但不知道是否成功 成功一般為2xx 失敗可能為4xx 5xx
if (request.status >= 200 && request.status <= 300) {
const style = document.createElement("style"); //創(chuàng)建style標(biāo)簽
style.innerHTML = request.response; //填寫style內(nèi)容
document.head.appendChild(style); //插入到head標(biāo)簽里面
} else {
alert("加載css失敗");
}
}
};
加載XML
步驟如下:
創(chuàng)建 HttpRequest 對象(全稱是 XMLHttpRequest)
調(diào)用對象的 open 方法
監(jiān)聽對象的 onreadystatechange 事件 ——在事件處理函數(shù)里操作 responseXML
調(diào)用對象的 send 方法(發(fā)送請求)
代碼演示:
//給XML事件一個監(jiān)聽
getXML.onclick = () => {
const request = new XMLHttpRequest();
request.open("GET", "/4.xml");
request.onreadystatechange = () => {
if (request.readyState === 4 && request.status === 200) {
const dom = request.responseXML; //DOM對象不止是用于HTMl也用于XML
const text = dom.getElementsByTagName("warning")[0].textContent; //注意要加[0]忆植,否則將會獲得一個偽數(shù)組
console.log(text.trim()); //trim一下可以消除回車
}
};
request.send();
};
小結(jié)
解析方法得到 CSS 之后生成 style 標(biāo)簽
得到 JS 之后生成 script 標(biāo)簽
得到 HTML 之后使用 innerHTML 和 DOM API
得到 XML 之后使用 responseXML 和 DOM API
不同類型的數(shù)據(jù)有不同類型的解析辦法
加載JSON
什么是JSON
JavaScript Object Notation
JSON是一門語言,是一門標(biāo)記語言谒臼,與HTML朝刊、XML、Markdown一樣用來展示數(shù)據(jù)
JSON支持的數(shù)據(jù)類型:number,bool,string,null,object,array
字符串用雙引號蜈缤,沒有undefined拾氓,不支持函數(shù),不支持變量
加載JSON
創(chuàng)建 HttpRequest 對象(全稱是 XMLHttpRequest)
調(diào)用對象的 open 方法
監(jiān)聽對象的 onreadystatechange 事件 ——在事件處理函數(shù)里使用 JSON.parse
調(diào)用對象的 send 方法(發(fā)送請求)
代碼演示:
//給JSON事件一個監(jiān)聽
getJSON.onclick = () => {
const request = new XMLHttpRequest();
request.open("GET", "/5.json");
request.onreadystatechange = () => {
if (request.readyState === 4 && request.status === 200) {
console.log(typeof request.response);
console.log(request.response);
const bool = JSON.parse(request.response); //SON 字符串 => JS 數(shù)據(jù),由于 JSON 只有六種類型底哥,所以轉(zhuǎn)成的數(shù)據(jù)也只有6種
console.log(typeof bool);
console.log(bool);
}
};
request.send();
};
這里用到了JSON.parse咙鞍,要用try catch 捕獲錯誤
let object;
try {
object = JSON.parse(`{'name':'origami'}`);
} catch (error) {
console.log("出錯了,錯誤詳情是");
console.log(error);
object = { name: "noname" };
}
console.log(object);