1.XMLHttpRequest是一个构造函数
2.ajax的使用步骤
2.1创建xhr对象
const xhr = new XMLHttpRequest();
2.2 准备发送请求
xhr.open(‘Http 方法 GET、POST、PUT、DELETE’,
‘远程地址 URL 或者本地文件./index.html ./index.xml ./index.txt’, true是否异步);
调用open并不会真正发送请求,而只是做好发送请求前的准备工作
2.3 发送请求
调用send()的参数是通过请求体(post)携带的数据;
如果是get方式,则要通过请求头即在url中携带,然后send(null)
2.4监听事件,处理响应
当获取到响应后,会触发xhr对象的readystatechange事件,可以在该事件中对响应进行处理
xhr.onreadystatechange = () => {
if (xhr.readyState !== 4) return;
//等于4说明网络传输过程没问题,但你的请求或者服务器端可能出现问题
//获取到响应后,响应的内容会自动填充xhr对象的属性
// HTTP CODE
//xhr.status: HTTP 200 ,404
//xhr.statusText:HTTP 状态说明 OK, NOT Found
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
// console.log('正常使用响应数据');
// console.log(xhr.responseText);
}else{}
}
readystatechange事件监听readystate这个状态的变化
它的值从0~4,一共5个状态
0: 未初始化。尚未调用open()
1: 启动。 已经调用open(),但尚未调用send()
2: 发送。已经调用send(),但尚未接收到响应
3: 接收。已经接收到部分响应数据
4: 完成。已经接收到全部响应数据,而且已经可以在浏览器中使用了
注意事项:监听最好放在open和send之前;
为了兼容性,在函数用xhr,不用this
<script>
const url = "http://www.imooc.com/api/http/search/suggest?words=html";
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = ()=>{
if(xhr.readyState!==4) return;
if((xhr.status >=200 && xhr.status <300) || xhr.status === 304){
console.log(xhr.responseText);
console.log(typeof xhr.responseText);
}
}
xhr.open('GET',url,true);
xhr.send(null)
</script>