2017-10-05 35 views
0

在下面的jQuery 中,可以將showLoader設置爲在發出AJAX請求時顯示加載圖標。jQuery AJAX自定義showLoader

$.ajax({ 
    url: baseUrl, 
    data: (paramData && paramData.length > 0 ? paramData + '&ajax=1' : 'ajax=1'), 
    type: 'get', 
    dataType: 'json', 
    cache: true, 
    showLoader: true, 
    timeout: 10000 
}); 

我想知道是否有自定義它,我已經爲加載圖標,使整個我的網站加載圖標均勻一些HTML有道。

回答

2

我可以同意戈帕爾,但要小心處理錯誤。如果請求失敗,加載器應該被隱藏,並且應該通知用戶。請參閱http://api.jquery.com/jquery.ajax/

完成回調更適合此目的,因爲它將被稱爲無論如何。

$.ajax({ 
    type: "GET", 
    url: "" 
    beforeSend: function(){ 
     $(".show_load_icon").show(); 
    }, 
    complete: function(){ 
     $(".show_load_icon").hide(); 
    } 
}); 

或者您可以手動處理錯誤。

$.ajax({ 
    type: "GET", 
    url: "" 
    beforeSend: function(){ 
     $(".show_load_icon").show(); 
    }, 
    success: function(){ 
     $(".show_load_icon").hide(); 
    }, 
    error: function(){ 
     $(".show_load_icon").hide(); 
     alert("Error"); // inform the user about error 
    } 
}); 

從jQuery的3.0,你可以使用.done()和.fail()

2

對於我的建議有默認AJAX showloader

所以,你可以去更好地爲這樣的選項。

$.ajax({ 
    type: "POST", 
    url: "someURL" 
    data: "someDataString", 
    beforeSend: function(msg){ 
     $(".show_load_icon").show(); 
    }, 
    success: function(msg){ 
     $(".show_load_icon").hide(); 
    } 
});