jQuery使用ajaxStart()和ajaxStop()方法


ajaxStart()ajaxStop()方法是綁定Ajax事件。ajaxStart()方法用於在Ajax請求發出前觸發函數,ajaxStop()方法用於在Ajax請求完成后觸發函數。它們的調用格式為:

$(selector).ajaxStart(function())$(selector).ajaxStop(function())

其中,兩個方法中括號都是綁定的函數,當發送Ajax請求前執行ajaxStart()方法綁定的函數,請求成功后,執行ajaxStop ()方法綁定的函數。

例如,在調用ajax()方法請求服務器數據前,使用動畫顯示正在加載中,當請求成功后,該動畫自動隱藏,如下圖所示:

在瀏覽器中顯示的效果:

從圖中可以看出,由於使用ajaxStart()ajaxStop()方法綁定了動畫元素,因此,在開始發送Ajax請求時,元素顯示,請求完成時,動畫元素自動隱藏。

注意:該方法在1.8.2下使用是正常的

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
<html xmlns="http://www.w3.org/1999/xhtml"
    <head> 
        <title>使用ajaxStart()和ajaxStop()方法</title> 
        <script src="http://libs.baidu.com/jquery/1.8.2/jquery.js" type="text/javascript"></script> 
        <link href="style.css" rel="stylesheet" type="text/css" /> 
    </head> 
    
    <body> 
        <div id="divtest"> 
            <div class="title"> 
                <span class="fl">加載一段文字</span> 
                <span class="fr"> 
                    <input id="btnShow" type="button" value="加載" /> 
                </span> 
            </div> 
            <ul> 
               <li id="divload"></li> 
            </ul> 
        </div> 
        
        <script type="text/javascript"> 
            $(function () { 
                $("#divload").ajaxStart(function(){ 
                    $(this).html("正在請求數據..."); 
                }); 
                $("#divload").ajaxStop(function(){ 
                    $(this).html("數據請求完成!"); 
                }); 
                $("#btnShow").bind("click", function () { 
                    var $this = $(this); 
                    $.ajax({ 
                        url: "http://www.imooc.com/data/info_f.php"
                        dataType: "json", 
                        success: function (data) { 
                            $this.attr("disabled", "true"); 
                        $("ul").append("<li>我的名字叫:" + data.name + "</li>"); 
                        $("ul").append("<li>男朋友對我說:" + data.say + "</li>"); 
                        } 
                    }); 
                }) 
            }); 
        </script> 
    </body> 
</html>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM