[TOC]
>[success] # onload和onreadystatechange
~~~
有'2'种事件可以获取接口返回值,'onload'等接口成功返回后,'onreadystatechange'只要状态码
(200、404....等等)改变了都会走这个事件,所以使用'onreadystatechange'时候需要做判断
~~~
1. 前端代码
~~~
Documentdiv {
width: 100px;
height: 100px;
background-color: green;
}
div:hover {
background: greenyellow;
}
window.onload = function () {
/*
异步对象:同事干很多事情
同步:一件事一件事的干
*/
// 1. onload方式
document.querySelector('input').onclick = function () {
// 1. 创建异步对象
var xhr = new XMLHttpRequest();
// 2. 设置请求行(get请求数据写在url后面)
// 使用同步的模式发送请求
// 参数3: 是否使用异步默认是true (异步)、false(同步)
// 同步 请求响应回来之前什么事都干不了
// 基本上不会使用这个模式, 知道有这个选项即可
xhr.open('get', 'xxx.php', false);
// 3. 设置请求头(get请求可以省略,post不发送数据也可以省略)
// 3.5 注册回调函数
xhr.onload = function () {
console.log(xhr.responseText)
}
// 4. 请求主体发送(get请求为空,或者写null,post请求数据写在这里,如果没有数据,直接为空或者写null)
xhr.send(null)
}
// 2. onreadystatechange方式
document.querySelector('.lastBtn').onclick = function () {
// 1. 创建异步对象
var xhr = new XMLHttpRequest();
// 2. 设置请求行(get请求数据写在url后面)
// 使用同步的模式发送请求
// 参数3: 是否使用异步默认是true (异步)、false(同步)
// 同步 请求响应回来之前什么事都干不了
// 基本上不会使用这个模式, 知道有这个选项即可
xhr.open('get', 'xxx.php', true);
// 3. 设置请求头(get请求可以省略,post不发送数据也可以省略)
// 3.5 注册回调函数
// 触发的次数多
// 状态改变时会触发
xhr.onreadystatechange = function () {
// 判断响应回来,并且请求的页面存在,采取获取数据
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.readyState)
console.log(xhr.responseText)
}
}
// 4. 请求主体发送(get请求为空,或者写null,post请求数据写在这里,如果没有数据,直接为空或者写null)
xhr.send(null)
}
}
异步对象
~~~
2. 后台代码
~~~
echo '奥利给';
sleep(5);
?>
~~~