重要參考
ajax與XMLHttpRequest
阮一峰 XMLHttpRequest Level 2 使用指南
- 手寫(xiě) 原生js實(shí)現(xiàn)ajax請(qǐng)求
const xhr = new XMLHttpRequest();
// 注意這里其實(shí)是可以用四三個(gè)參數(shù)的,
// true表示異步請(qǐng)求
// false表示同步請(qǐng)求,
xhr.open('GET', 'http://www.zhengshengliang.com:9999/');
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) { // 注意readyState大寫(xiě)
console.log('請(qǐng)求都相應(yīng)完畢了');
if (xhr.status >= 200 && xhr.status < 300) {
console.log('相應(yīng)成功');
const res = xhr.responseText; // 你才返回對(duì)象,你全家才返回對(duì)象 作為http的第四部分,返回的永遠(yuǎn)是字符串
console.log(typeof res); // "string"
let obj = window.JSON.parse(res);
} else if (xhr.status >= 400) {
console.log('相應(yīng)失敗');
}
}
}
xhr.ontimeout = (e) => {
alert('請(qǐng)求超時(shí)了');
}
xhr.timeout = 3000; // 3000ms超時(shí)
xhr.send();
// 若為異步(true),則先打印1,后打印請(qǐng)求內(nèi)容
// 若為同步(false),則先打印請(qǐng)求內(nèi)容,后打印1
console.log(1);
json 和 js的區(qū)別
json是一門(mén)語(yǔ)言,javascript也是一門(mén)語(yǔ)言(發(fā)明者Brendan Eich 布蘭登·艾克)。json(發(fā)明者道格拉斯·克羅克福特 Douglas Crockford)是抄襲JavaScript的。JSON沒(méi)有抄襲 js中的function 和 undefined
JSON的字符串首尾必須是 ""
https://www.json.org/ 火車(chē)圖
"leon" 是json
null 是json
{'name': leon} 不是json 因?yàn)槭孜矝](méi)有雙引號(hào)