服务端php添加了sleep延迟5秒执行
服务端代码demo.php
<?php sleep(5); $name=$_POST; var_dump($name); ?>
同步请求
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>ajax</title> </head> <body> <button id=button>发送请求</button> <div id="container"> </div> </body> <script> //获取按钮 var button = document.getElementById('button'); var container = document.getElementById('container'); button.onclick=function(){ //创建xmlhttpRequest请求 var xhr = new XMLHttpRequest(); //准备发送请求方式 xhr.open('POST','demo.php',false); //发送请求 //编码转换 xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); xhr.send('name=jiub&age=12'); //接受并处理请求返回的数据 var response = xhr.responseText; console.log(response); container.innerHTML=response; alert('执行完毕'); } </script> </html>
点击发送请求,ajax会等待服务端响应完毕才会弹出alert,这样很影响用户体验,影响js dom
异步请求
点击发送请求,服务端无响应,前端js正常执行,服务端响应成功后反回数据
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>ajax</title> </head> <body> <button id=button>发送请求</button> <div id="container"> </div> </body> <script> //获取按钮 var button = document.getElementById('button'); var container = document.getElementById('container'); button.onclick=function(){ //创建xmlhttpRequest请求 var xhr = new XMLHttpRequest(); //异步请求方式 xhr.onreadystatechange = function(){ if(xhr.readyState == 4 && xhr.status == 200){ var response = xhr.responseText; container.innerHTML=response; } } //准备发送请求方式 xhr.open('POST','demo.php',true); //发送请求 //编码转换 xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); xhr.send('name=jiub&age=12'); //接受并处理请求返回的数据 // var response = xhr.responseText; // console.log(response); // container.innerHTML=response; alert('执行完毕'); } </script> </html>
加群入久伴博客官方微信群
加入久伴官方微信群有啥优势?
1.文章内部资源由于时间久远可能失效,加群,群内可以第一时间反馈
2.网站中教程不一定适用任何人,加群可以第一时间咨询并解决您得疑惑
3.你游荡于互联网,也需要群体,加群一起互动交流,畅所欲言
扫描下方二维码即可加入交流讨论
