get請求ajax
//get請求 const xhr = new XMLHttpRequest() xhr.open("GET","/api",false)//false表示請求方式爲異步 xhr.onreadystatechange = function () { if(xhr.readyState === 4){ if(xhr.status === 200){ console.log(JSON.parse(xhr.responseText))//轉化成json格式 } } } xhr.send(null)
post請求json
const xhr = new XMLHttpRequest() xhr.open("POST","/login",false) xhr.onreadystatechange = function () { if(xhr.readyState === 4){ if(xhr.status === 200){ console.log(JSON.parse(xhr.responseText)) } } } const postData = { username:'張三', password:'123456' } xhr.send(JSON.stringify(postData))//發送字符串