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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值