// const xhr = new XMLHttpRequest()
// //true支持异步
// xhr.open(‘get‘, ‘/work1/javascript/ajax/ziyuan.json‘, true)
// xhr.onreadystatechange = function() {
// if(xhr.readyState === 4) {
// if(xhr.status === 200) {
// console.log(JSON.parse(xhr.responseText))
// }
// }
// }
// xhr.send(null)
function ajax(url) {
const p = new Promise( (resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.open(‘get‘, url, true)
xhr.onreadystatechange = function() {
if(xhr.readyState === 4) {
if(xhr.status === 200) {
resolve(xhr.responseText)
}else if(xhr.status === 404) {
reject(‘404 server ‘)
}
}
}
xhr.send(null)
})
return p
}
ajax(‘/work1/javascript/ajax/ziyuan.json‘).then( data => {
console.log(data)
}).catch( err => {
cosole.log(err)
})
手写ajax