XMLHttpRequest
的基本使用
这种知识点用到时翻翻就行了,不必死记住。
XMLHttpRequest( 简称 xhr ) 是浏览器提供的JavaScript对象,通过它,可以请求服务器上的数据资源。
1.使用xhr
发起GET请求
步骤
-
创建
xhr
对象 -
调用
xhr.open()
函数 -
调用
xhr.send()
函数 -
监听
xhr.onreadystatechange
事件
// 1. 创建 XHR 对象
var xhr = new XMLHttpRequest()
// 2. 调用 open 函数
xhr.open('GET', 'url')
// 3. 调用 send 函数
xhr.send()
// 4. 监听 onreadystatechange 事件
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
// 获取服务器响应的数据
console.log(xhr.responseText)
}
}
<