Ajax请求
-
创建
XMLHttpRequest
对象if(window.XMLHttpRequest){ let xrh = new XMLHttpRequest() // ie6及以上的浏览器 }else{ let xrh= new ActiveXObject("Microsoft.XMLHTTP") // ie5及以下的浏览器 }
-
向服务器发送请求
xrh.open(method,url,async) // method:请求方式,url:请求地址,async:是否异步,布尔值,默认为true xrh.send()
-
获取服务器返回的数据
// 请求成功所执行的函数 xrh.onload = function(){ // xrh.readyState == 4 && xrh.status == 200 console.log(xrh.response) // xrh.response 请求成功后服务器返回的信息 } xrh.onerror=function(error){ console.log(error) }
实例
let xrh = new XMLHttpRequest(); xrh.open(type,'http://127.0.0.1:8000/resume/test'); xrh.onload = function(){ // xrh.readystate == 4 && xrh.status == 200 console.log(xrh.response) } xrh.onerror=function(error){ console.log(error) } xrh.send()
配置请求头
如果请求方式为POST,根据后台接受数据的形式,我们往往需要配置我们的请求头
xrh.setRequestHeader("Content-type","application/x-www-form-urlencoded")
// 不同的数据形式配置不同的请求头
// 1、表单形式:application/x-www-form-urlencoded;charset=UTF-8
// 2、json:'application/json;charset=UTF-8'
Promise 解决异步的问题
function ajax({url='',type='get'}){
return new Promise((resolve,reject)=>{ // resolve:执行成功的函数,reject:执行失败的函数
let xrh = new XMLHttpRequest();
xrh.open(type,'http://127.0.0.1:8000/resume/test');
xrh.onload = function(){ // xrh.readystate == 4 && xrh.status == 200
resolve(xrh.response)
}
xrh.onerror=function(error){
reject(error)
}
xrh.send()
})
}
ajax()((res)=>{ // 执行成功的函数
console.log(res)
},(error)=>{ // 执行失败的函数
console.log(error)
})