shuman

[jquery-ajax] jquery ajax 三种情况对比

<button class="btn1">async:false</button>
<button class="btn2">setTimeout</button>
<button class="btn3">deferred</button>
    
<img class="loadingicon" style="position:fixed;left:50%;top:50%;margin-left:-16px;margin-top:-16px;display:none;" src="loading.gif" alt="正在加载" />
<!--
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
 -->
 
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script>

    function getData1(){
        var result;
        $.ajax({
            url : \'p.php\',
            async : false,
            success: function(data){
                result = data;
            }
        });

        return result;
    }

    $(\'.btn1\').click(function(){
        $(\'.loadingicon\').show();
        var data = getData1();
        $(\'.loadingicon\').hide();
        alert(data);
    });


    
    $(\'.btn2\').click(function(){
        $(\'.loadingicon\').show();
        setTimeout(function(){
            $.ajax({
                url : \'p.php\',
                async : false,
                success: function(data){
                    $(\'.loadingicon\').hide();
                    alert(data);
                }
            });
        }, 0);
    });


    function getData3(){
        var defer = $.Deferred();
        $.ajax({
            url : \'p.php\',
            //async : false,
            success: function(data){
                defer.resolve(data)
            }
        });
        return defer.promise();
    }    

    $(\'.btn3\').click(function(){
        $(\'.loadingicon\').show();
        $.when(getData3()).done(function(data){
            $(\'.loadingicon\').hide();
            alert(data);
        });
    });</script>

 

分类:

技术点:

相关文章:

  • 2021-06-19
  • 2021-08-05
  • 2022-02-16
  • 2021-10-25
  • 2021-11-15
  • 2021-12-16
猜你喜欢
  • 2021-07-04
  • 2022-01-15
  • 2021-10-07
  • 2021-09-25
  • 2021-09-25
  • 2021-09-25
相关资源
相似解决方案