ajax回傳完畢前的讀取畫面、css置中等功能

要完全置中(上下左右)
<style>
    .dialogbox{
        top: 0;
        left: 0;
        bottom: 0;
        right: 0;
        margin: auto;
        overflow: auto;
    }
</style>



在ajax的運用中使用,用途為若api未回傳資料回來,就插入畫面擋住不讓用戶一直點擊

CSS
div.loadingdiv {
    height: 100%;
    /*100%覆蓋網頁內容, 避免userloading時進行其他操作*/    width: 100%;
    position: fixed;
    z-index: 99999;
    /*須大於網頁內容*/    top: 0;
    left: 0;
    display: block;
    background: #000;
    opacity: 0.6;
    text-align: center;
}

div.loadingdiv img {
    position: relative;
    vertical-align: middle;
    text-align: center;
    margin: 0 auto;
    margin-top: 50vh;
}
Ajax
主要是在beforeSend跟complete這兩個function
若開始執行 show,若完成就hide。
AjaxCall: function (urlStr, object, callback) {
    console.log([urlStr, object]);
    $.ajax({
        url: urlStr,
        type: "GET",
        data: object,
        dataType: "json",
        success: function (data) {
            console.log(data);
            callback(data);
        },
        error: function (data) {
            callback(data);
        },
        beforeSend: function () {
            $('#loading').show();
        },
        complete: function () {
            $('#loading').hide();
        }
    });
}
Html
起始需設置為nono 避免擋住,img可置換為text或是其他圖片皆可
<div class="loadingdiv" id="loading" style="display: none">
    <img class="loading" src="image/ajax-loader.gif" alt="">
</div>

但是這個方法的缺點是,如果api的ajax一直沒有完成,畫面就有可能卡住在讀取條的畫面上,會一直卡住沒有辦法切換






留言

這個網誌中的熱門文章

jQuery獲取Select選擇的Text和Value(轉)

Android 在Fragment下控制輸入鍵盤

彈跳視窗iframe的運用