使用es6的promise
创建promise的实例对象
执行体里使用XMLHttpRequest创建实例
实例静态方法open(‘请求方法’,‘请求地址’)
实例静态方法send发送
监听xhr上的load事件
xhr.response或者xhr.responseText可以获取JSON格式数据,转换并改变promise状态,返回成功后的值
并return出去,调用可以使用p可以通过.then或者async await 获取成功后的值
function p (methods, url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.open(methods, 'http://127.0.0.1:2000' + url)
xhr.send()
xhr.addEventListener('load', () => {
// console.log(JSON.parse(xhr.responseText))
// console.log(JSON.parse(xhr.response))
resolve(JSON.parse(xhr.response))
})
})
}
export default p
封装
引入
点击事件
<button @click="doExpress">点击express请求</button>
执行函数
doExpress () {
axios('get', '/admin/search/?id=99').then(res => {
console.log(res)
})
效果