说下 Ajax
Asynchronous JavaScript + XML(异步 JavaScript 和 XML)。 XMLHttpRequest
API 是 Ajax 的核心。 使用 XMLHttpRequest - Web API 接口参考 | MDN (mozilla.org)
js
// 封装 ajax
function ajax(url, callback) {
let xmlhttp = null
// 1. 创建 XMLHttpRequest 对象
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest()
} else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP')
}
// 2. 发送请求
xmlhttp.open('GET', url)
xmlhttp.send()
// 3. 服务端响应
xmlhttp.onreadystatechange = function() {
if(
xmlhttp.readyState === 4 &&
xmlhttp.status === 200
) {
let res = JSON.parse(xmlhttp.responseText)
console.log(res)
callback(res)
}
}
}
let url = 'xxx'
ajax(url, res => {
console.log(res)
})
Fetch
Fetch API 提供了一个获取资源的接口(包括跨域请求)。任何使用过 XMLHttpRequest
的人都能轻松上手,而且新的 API 提供了更强大和灵活的功能集。 Fetch API - Web API 接口参考 | MDN (mozilla.org)