• 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     });
  • 相关阅读:
    List of all Oracle Server Parameters
    dbcc Trace
    站在巨人的肩膀上 书籍推荐 (zz)
    浅谈JS包装对象
    与 JavaScript 模块相关的所有知识点
    你真的懂Promise吗
    vue动态绑定class与style总结
    vue使用axios实现excel文件下载的实现
    CSRF 与 XSS
    推荐10个很棒的 JS 库
  • 原文地址:https://www.cnblogs.com/comrd/p/3596261.html
Copyright © 2020-2023  润新知