在开发中我们应该不会去使用原生的ajax请求去做业务。封装好的工具比原生要好用得多,开发效率也比原生要高得多。按理说他老人家应该退出历史舞台了,但是他在程序调试中的地位依然不可动摇。所以将他的基本使用方法记录一下,以备后面用到他的时候方便查找。
//原生ajax发起get请求
const xhr = new XMLHttpRequest()
xhr.open('get','http://127.0.0.1:8100/server?type=pop&page=1')
xhr.send()
xhr.onreadystatechange = ()=>{
if(xhr.readyState === 4){
//json字符串转换为json对象
const obj = JSON.parse(xhr.response)
}
}
//原生ajax发起post请求
var xhr = new XMLHttpRequest()
xhr.open('post','http://127.0.0.1:8100')
//设置请求头
//xhr.setRequestHeader('Token','notyer')
//设置请求体
xhr.send('{"username":"noty","password":"123456"}')
xhr.onreadystatechange = ()=>{
if(xhr.readyState === 4){
//json字符串转换为json对象
const obj = JSON.parse(xhr.response)
}
}