ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[TOC] >[success] # onload和onreadystatechange <br/> ~~~ 有'2'种事件可以获取接口返回值,'onload'等接口成功返回后,'onreadystatechange'只要状态码 (200、404....等等)改变了都会走这个事件,所以使用'onreadystatechange'时候需要做判断 ~~~ <br/> 1. 前端代码 ~~~ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> div { width: 100px; height: 100px; background-color: green; } div:hover { background: greenyellow; } </style> <script> 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) } } </script> </head> <body> <h2>异步对象</h2> <input type="button" value="ajax请求"> <input type="button" class="lastBtn" value="ajax请求2"> <div></div> </body> </html> ~~~ <br/> 2. 后台代码 ~~~ <?php echo '奥利给'; sleep(5); ?> ~~~