How can I create a “Please Wait, Loading…” animation using jQuery?

后端 未结 17 1976
长情又很酷
长情又很酷 2020-11-22 00:07

I would like to place a \"please wait, loading\" spinning circle animation on my site. How should I accomplish this using jQuery?

17条回答
  •  [愿得一人]
    2020-11-22 00:35

    You can grab an animated GIF of a spinning circle from Ajaxload - stick that somewhere in your website file heirarchy. Then you just need to add an HTML element with the correct code, and remove it when you're done. This is fairly simple:

    function showLoadingImage() {
        $('#yourParentElement').append('
    Loading...
    '); } function hideLoadingImage() { $('#loading-image').remove(); }

    You then just need to use these methods in your AJAX call:

    $.load(
         'http://example.com/myurl',
         { 'random': 'data': 1: 2, 'dwarfs': 7},
         function (responseText, textStatus, XMLHttpRequest) {
             hideLoadingImage();
         }
    );
    
    // this will be run immediately after the AJAX call has been made,
    // not when it completes.
    showLoadingImage();
    

    This has a few caveats: first of all, if you have two or more places the loading image can be shown, you're going to need to kep track of how many calls are running at once somehow, and only hide when they're all done. This can be done using a simple counter, which should work for almost all cases.

    Secondly, this will only hide the loading image on a successful AJAX call. To handle the error states, you'll need to look into $.ajax, which is more complex than $.load, $.get and the like, but a lot more flexible too.

提交回复
热议问题