javascript原生态的同步异步请求实现

 1 <script>
 2     //同步请求
 3     function sync_test(){
 4         //实例化XmlHttpRequest对象
 5         var xhr=new XMLHttpRequest();
 6         //使用GET方式请求指定网址的页面
 7         xhr.open("GET","http://www.baidu.com",false);
 8         //发送空内容请求
 9         xhr.send(null);
10 
11         if(xhr.status===200){//200状态码表示正常
12             alert(xhr.responseText);
13         }else{
14             alert("Error occurred:"+xhr.statusText);
15         }    
16     }
17 
18     //异步请求
19     function async_test(){
20         //实例化XmlHttpRequest对象
21         var xhr=new XMLHttpRequest();
22         //使用GET方式请求指定网址的页面
23         xhr.open("GET","http://www.baidu.com",true);
24         //添加回调函数
25         xhr.onreadystatechange=function(){
26             if(xhr.readyState===4){//4意味着处理完成
27                 if(xhr.status===200){
28                     alert(xhr.responseText);
29                 }else{
30                     alert("Error occurred:"+xhr.statusText);
31                 }
32             }
33         };
34         //发送空内容请求
35         xhr.send(null);    //注意:回调函数必须在xhr.send(null)之前调用,否则无法调用    
36     }
37   </script>
 1 //jQuery实现同步异步请求:
 2     $.ajax("baidu.com").done(function(data){//done()等价于旧版的success()
 3         alert(data);
 4     }).fail(function(xhr){//fail()等价于旧版的error()
 5         alert("Error occurred:"+xhr.statusText);
 6     });
 7     //jQuery默认就是Get和异步请求方式,如果要更改这些,则以下这种写法:
 8     $.ajax({
 9         url:"baidu.com",
10         async:false,//表示同步请求
11         type:"GET",//Get或者Post,默认Get方式
12         done:function(data){
13             alert(data);
14         }
15         fail:function(xhr){
16             alert(""+xhr.statusText);
17         }
18     });
原文地址:https://www.cnblogs.com/comrd/p/3596261.html