同步和异步请求

同步:一步步来,单线程
异步:在没有加载完就执行后面的代码,所以要注册请求状态用以监视来执行回调函数(服务器接收了请求如何响应)

var request = new XMLHttpRequest(); //创建对象
request.open('GET', 'https://developer.mozilla.org/', false); //初始化同步请求
request.send(null);//发送请求
if (request.status === 200) {
console.log(request.responseText);
}//回调函数

>undefined
GET
https://developer.mozilla.org/ [HTTP/1.1 301 MOVED PERMANENTLY 1449ms]
GET
https://developer.mozilla.org/zh-CN/ [HTTP/1.1 200 OK 1176ms]
"..."

var request = new XMLHttpRequest();
request.open('GET', 'https://developer.mozilla.org/', true); //异步请求
request.send(null);
if (request.status === 200) {
console.log(request.status);
}
>undefined
GET

var request = new XMLHttpRequest();
request.onreadystatechange = mantou;//注册状态监视函数
request.open('GET', 'https://developer.mozilla.org/', true); //异步请求
request.send(null);
function mantou(){if (request.status === 200) {
console.log(request.status);
}}
>undefined
GET
https://developer.mozilla.org/zh-CN/ [HTTP/1.1 200 OK 8424ms]
200