const getJSON = function (url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
// 第三个参数表示是异步还是同步,true表示异步,false表示同步
xhr.open('GET', url, true)
xhr.onreadystatechange = function () {
// readyState
// 0:未初始化。尚未调用open()方法。
// 1:启动。已经调用open()方法,但尚未调用send()方法。
// 2:发送。已经调用send()方法,但尚未接收到响应
// 3:接收。已经接收到部分相应数据
// 4:完成。已经接收到全部响应数据,而且已经可以在客户端使用。
if (xhr.readyState !== 4) {
return
}
if (xhr.status === 200) {
resolve(xhr.responseText)
} else {
reject(new Error(xhr.statusText))
}
}
xhr.responseType = 'json'
xhr.setResponseHeader('Accept', 'application/json')
xhr.send(null)
})
}
getJSON('/posts.json').then(function (json) {
console.log(json)
}, function (error) {
console.log(error)
})