2010-05-27 72 views
4

如何向用戶顯示加載圖片和/或消息? 如果可能,我想知道如何使它成爲灰色背景的全屏幕。有點像從一些畫廊查看大圖片(對不起,沒有示例鏈接)。如何顯示jQuery正在工作/等待/正在加載?

當前我添加一個CSS類,它具有圖像和其他格式,但由於某種原因它不工作。 搜索結果會插入到div中。

HTML

<div id="searchresults"></div> 

CSS

div.loading { 
    background-image: url('../img/loading.gif'); 
    background-position: center; 
    width: 80px; 
    height: 80px; 
} 

JS

$(document).ready(function(){ 
    $('#searchform').submit(function(){ 
    $('#searchresults').addClass('loading'); 
    $.post('search.php', $('#'+this.id).serialize(),function(result){ 
     $('#searchresults').html(result); 
    }); 
    $('#searchresults').removeClass('loading'); 
    return false; 
    }); 
}); 

回答

2

你的問題是,你在呼喚你​​發出Ajax調用後,它完成而不是之後。

你可以在ajax回調中做​​。 $.post允許只提供success回調:

jQuery.post(url, [ data ], [ success(data, textStatus, XMLHttpRequest) ], [ dataType ]) 

和加載圖片應該在任何情況下被刪除 - 更迭或失敗,所以最好使用complete回調$.ajax()

$('#searchform').submit(function(){ 
    $('#searchresults').addClass('loading'); 

    $.ajax({ 
    type: 'POST', 
    url: 'search.php', 
    data: $('#'+this.id).serialize(), 
    success: function(result){ 
     $('#searchresults').html(result); 
    }, 
    complete: function() { 
     $('#searchresults').removeClass('loading'); 
    } 
    }); 
    return false; 
}); 

查看更多有關「回調函數」中的回調部分$.ajax() docs

0

試試這個:

$("#contentLoading").ajaxSend(function(r, s) { 
     $(this).show(); 
     $("#ready").hide(); 
    }); 

    $("#contentLoading").ajaxStop(function(r, s) { 
     $(this).hide(); 
     $("#ready").show(); 
    }); 

這將顯示#contentLoading這是我的進展gif當我啓動ajax並在ajax停止時隱藏它。

相關問題