目錄
1-get方法提交
- 狀態值
0 (未初始化)對象已建立,但是尚未初始化(尚未調用open方法)
1(初始化)已調用send()方法,正在發送請求
2(發送數據)send()方法調用完成,但是當前的狀態及http頭未知
3(數據傳送中)已接收部分數據,因為相應及http頭不全,這時通過responseText獲取部分數據會出現錯誤
4(完成)數據接收完成,此時可以通過responseText獲取完整的數據
- json轉換
JSON.parse() 字符串轉對象
JSON.stringify() 對象轉字符串
- get寫法
const xhr = new XMLHttpRequest()
xhr.onreadystatechange = () = {
if(xhr.readyState === 200 && xhr.status === 200){
console.log(xhr.responseText)
}//readyState 準備狀態 status 請求狀態
}
xhr.open('GET', 'http://localhost:3000/get?x=1', true)
xhr.send()
open() 這個方法有三個參數,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}`)