同步:一堆任务,按顺序去执行,只能一件件的来,如一个厨师做菜
异步:一堆任务,可以同时进行,如多个厨师做菜
ajax请求默认是异步的,它的open("get","data.php",true),第三个参数true表示异步,false表示同步,默认是true
当请求是同步的时候,监听事件在send()后面就接收不到了,因为发生完就已经响应完了.此时才去监听
<!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> </head> <body> <button id="btn">发送请求</button> </body> </html> <script> var btn=document.getElementById("btn");//获取元素 btn.onclick=function(){ var xhr=new XMLHttpRequest();//创建请求对象 IE6和之前不支持这个对象使用 new ActiveObject()做兼容,具体百度下 if(!xhr){ //不兼容时 xhr=new ActiveXObject("Microsoft.XMLHTTP"); } xhr.open("post","/login.jsp");//设置请求行,第三个参数默认为true,表示异步,如果写了false代表同步,此时监听事件就要写在send方法之前才能监听到结果 xhr.setRequestHeader("content-type","application/x-www-form- urlencoded");//post请求需要设置请求头,get不用 xhr.send("username=yang&age=18");//设置请求体,get请求不用设置参数,它的参数拼接到url中 xhr.onreadystatechange=function(){ //onload方法就不用判断下面的状态了,但它在有些浏览器中不兼容 if(xhr.readyState==4 && xhr.status==200){ xhr.responseText;//这是响应体 } } } </script>