目錄
1-get方法提交
- 狀態(tài)值
0 (未初始化)對象已建立蔬胯,但是尚未初始化(尚未調(diào)用open方法)
1(初始化)已調(diào)用send()方法帚戳,正在發(fā)送請求
2(發(fā)送數(shù)據(jù))send()方法調(diào)用完成灰嫉,但是當(dāng)前的狀態(tài)及http頭未知
3(數(shù)據(jù)傳送中)已接收部分?jǐn)?shù)據(jù)示血,因為相應(yīng)及http頭不全奈附,這時通過responseText獲取部分?jǐn)?shù)據(jù)會出現(xiàn)錯誤
4(完成)數(shù)據(jù)接收完成,此時可以通過responseText獲取完整的數(shù)據(jù)
- json轉(zhuǎn)換
JSON.parse() 字符串轉(zhuǎn)對象
JSON.stringify() 對象轉(zhuǎn)字符串
- get寫法
const xhr = new XMLHttpRequest()
xhr.onreadystatechange = () = {
if(xhr.readyState === 200 && xhr.status === 200){
console.log(xhr.responseText)
}//readyState 準(zhǔn)備狀態(tài) status 請求狀態(tài)
}
xhr.open('GET', 'http://localhost:3000/get?x=1', true)
xhr.send()
open() 這個方法有三個參數(shù)朱庆,open("提交方式 get/post","資源的地址",異步或者同步 true/false);
2-post方法提交
const xhr = new XMLHttpRequest()
const data = {
name:'xiaopan',
age:'22'
}
xhr.onreadystatechange = () => {
if(xhr.readyState === 4 && xhr.status === 200){
console.log(JSON.parse(xhr.responseText))
}
}
xhr.open('post', 'http://localhost:3000/post', true)
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencouded')
xhr.send(`username=${data.name}&age=${data.age}`)