开发者

Display 'loading' image when AJAX call is in progress

I have the following jQuery Ajax call:

$.ajax({
                   type: "POST",
                   url: "addtobasket.php",
                   data: "sid=<?= $sid ?>&itemid=" + itemid + "&boxsize=" + boxsize + "&ext=" + extraval,
                   success: function(msg){
                     $.post("preorderbasket.php", { sid: "<?= $sid ?>", type: "pre" },
                     function(data){
                        $('.preorder').empty();
                         $('.preorder').append(data); 
                     }); 
                   }
                 });
开发者_JAVA百科

I want to display an image when the ajax call is in progress. How can I do that?

Thanks,


try this :

<script type="text/javascript">
    $(document).ready(function()
    {
        $('#loading')
            .hide()
            .ajaxStart(function() {
                $(this).show();
            })
            .ajaxStop(function() {
                $(this).hide();
            });
    });
</script>

<div id="loading">
        Loading....
</div>

This will show the loading image each time you are doing an ajax request, I have implented this div at the top of my pages, so it does not obstruct with the page, but you can always see when an ajax call is going on.


Something along these lines (showLoadingImage and hideLoadingImage are up to you):

// show the loading image before calling ajax.
showLoadingImage();

$.ajax({
    // url, type, etc. go here
    success: function() {
        // handle success. this only fires if the call was successful.
    },
    error: function() {
        // handle error. this only fires if the call was unsuccessful.
    },
    complete: function() {
        // no matter the result, complete will fire, so it's a good place
        // to do the non-conditional stuff, like hiding a loading image.

        hideLoadingImage();
    }
});


You can display the image just before this call to $.ajax() and then hide/remove the image in the post handler function (just before your .empty()/.append(data) calls.


It works. I have tested it.

<script type='text/javascript'>

$(document).ready(function(){

$("#but_search").click(function(){
var search = $('#search').val();

$.ajax({
 url: 'fetch_deta.php',
type: 'post',
data: {search:search},
beforeSend: function(){
 // Show image container
$("#loader").show();
},
success: function(response){
 $('.response').empty();
$('.response').append(response);
},
complete:function(data){
// Hide image container
$("#loader").hide();
}
});

});
});
</script>

<input type='text' id='search'>
<input type='button' id='but_search' value='Search'><br/>

<!-- Image loader -->
<div id='loader' style='display: none;'>
  <img src='reload.gif' width='32px' height='32px'>
</div>
<!-- Image loader -->

<div class='response'></div>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜