Jak pokazać wczytywanie spinnera w jQuery?

W prototypie mogę pokazać " Ładowanie..."obrazek o tym kodzie:

var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars, 
onLoading: showLoad, onComplete: showResponse} );

function showLoad () {
    ...
}

W jQuery mogę załadować stronę serwera do elementu o następującej treści:

$('#message').load('index.php?pg=ajaxFlashcard');

Ale jak podłączyć spinner do tego polecenia, tak jak to zrobiłem w prototypie?

Author: Danil Speransky, 2008-09-16

24 answers

Jest kilka sposobów. Moim preferowanym sposobem jest dołączenie funkcji do zdarzeń ajaxStart/Stop na samym elemencie.

$('#loadingDiv')
    .hide()  // Hide it initially
    .ajaxStart(function() {
        $(this).show();
    })
    .ajaxStop(function() {
        $(this).hide();
    })
;

Funkcje ajaxStart/Stop będą uruchamiane za każdym razem, gdy wykonasz jakiekolwiek połączenia Ajax.

Update: od wersji jQuery 1.8 dokumentacja stwierdza, że .ajaxStart/Stop powinna być dołączona tylko do document. To przekształci powyższy fragment do:

var $loading = $('#loadingDiv').hide();
$(document)
  .ajaxStart(function () {
    $loading.show();
  })
  .ajaxStop(function () {
    $loading.hide();
  });
 751
Author: nickf,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-11 19:57:19

Do jQuery używam

jQuery.ajaxSetup({
  beforeSend: function() {
     $('#loader').show();
  },
  complete: function(){
     $('#loader').hide();
  },
  success: function() {}
});
 195
Author: kr00lix,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-05-04 18:57:57

Możesz po prostu użyć funkcji jQuery .ajax i użyć jej opcji beforeSend i zdefiniować jakąś funkcję, w której możesz pokazać coś w rodzaju Loader div, a przy opcji success możesz ukryć ten Loader div.

jQuery.ajax({
    type: "POST",
    url: 'YOU_URL_TO_WHICH_DATA_SEND',
    data:'YOUR_DATA_TO_SEND',
    beforeSend: function() {
        $("#loaderDiv").show();
    },
    success: function(data) {
        $("#loaderDiv").hide();
    }
});

Możesz mieć dowolny obracający się obraz Gif. Oto strona, która jest świetnym generatorem AJAX Loader zgodnie z Twoim schematem kolorów: http://ajaxload.info/

 33
Author: Seeker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-17 16:00:08

Możesz wstawić animowany obraz do DOM tuż przed wywołaniem AJAX i wykonać funkcję inline, aby go usunąć...

$("#myDiv").html('<img src="images/spinner.gif" alt="Wait" />');
$('#message').load('index.php?pg=ajaxFlashcard', null, function() {
  $("#myDiv").html('');
});

Spowoduje to, że Twoja animacja rozpocznie się w tej samej klatce przy kolejnych żądaniach (jeśli to ma znaczenie). Zauważ, że stare wersje IE mogą mieć problemy z animacją.

Powodzenia!
 22
Author: Josh Stodola,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-09-16 01:28:12
$('#message').load('index.php?pg=ajaxFlashcard', null, showResponse);
showLoad();

function showResponse() {
    hideLoad();
    ...
}

Http://docs.jquery.com/Ajax/load#urldatacallback

 20
Author: UltimateBrent,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-03-19 02:00:51

Jeśli używasz $.ajax() możesz użyć czegoś takiego:

$.ajax({
        url: "destination url",
        success: sdialog,
        error: edialog,
        // shows the loader element before sending.
        beforeSend: function () { $("#imgSpinner1").show(); },
        // hides the loader after completion of request, whether successfull or failor.             
        complete: function () { $("#imgSpinner1").hide(); },             
        type: 'POST', dataType: 'json'
    });  
 14
Author: AminSaghi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-06-05 11:09:43

Użyj wtyczki ładowania: http://plugins.jquery.com/project/loading

$.loading.onAjax({img:'loading.gif'});
 10
Author: Nathan Bubna,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-09-28 06:48:12

Variant: mam ikonę z id = "logo" w lewym górnym rogu strony głównej; GIF spinner jest następnie nakładany na górę (z przezroczystością), gdy ajax działa.

jQuery.ajaxSetup({
  beforeSend: function() {
     $('#logo').css('background', 'url(images/ajax-loader.gif) no-repeat')
  },
  complete: function(){
     $('#logo').css('background', 'none')
  },
  success: function() {}
});
 8
Author: Paul,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-05-02 22:41:38

Skończyłem z dwoma zmianami w oryginalnej odpowiedzi .

  1. od wersji jQuery 1.8, ajaxStart i ajaxStop powinny być dołączane tylko do document. Utrudnia to filtrowanie tylko niektórych żądań ajax. Soo...
  2. przełączenie na ajaxSendi ajaxComplete umożliwia interspektowanie bieżącego żądania ajax przed pokazaniem spinnera.

Oto kod po tych zmianach:

$(document)
    .hide()  // hide it initially
    .ajaxSend(function(event, jqxhr, settings) {
        if (settings.url !== "ajax/request.php") return;
        $(".spinner").show();
    })
    .ajaxComplete(function(event, jqxhr, settings) {
        if (settings.url !== "ajax/request.php") return;
        $(".spinner").hide();
    })
 7
Author: Emil Stenström,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:03:05

Chcę również przyczynić się do tej odpowiedzi. Szukałem czegoś podobnego w jQuery i to, czego ostatecznie użyłem.

Dostałem swój spinner z http://ajaxload.info/. moje rozwiązanie opiera się na tej prostej odpowiedzi na http://christierney.com/2011/03/23/global-ajax-loading-spinners/.

Zasadniczo znaczniki HTML i CSS wyglądałyby tak:

<style>
     #ajaxSpinnerImage {
          display: none;
     }
</style>

<div id="ajaxSpinnerContainer">
     <img src="~/Content/ajax-loader.gif" id="ajaxSpinnerImage" title="working..." />
</div>

A potem kod do jQuery wyglądałby jak to:

<script>
     $(document).ready(function () {
          $(document)
          .ajaxStart(function () {
               $("#ajaxSpinnerImage").show();
          })
          .ajaxStop(function () {
               $("#ajaxSpinnerImage").hide();
          });

          var owmAPI = "http://api.openweathermap.org/data/2.5/weather?q=London,uk&APPID=YourAppID";
          $.getJSON(owmAPI)
          .done(function (data) {
               alert(data.coord.lon);
          })
          .fail(function () {
               alert('error');
          });
     });
</script>

To takie proste:)

 7
Author: Brendan Vogt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-21 09:17:49

Możesz po prostu przypisać obraz loadera do tego samego znacznika, na którym później załadujesz zawartość za pomocą wywołania Ajax:

$("#message").html('<span>Loading...</span>');

$('#message').load('index.php?pg=ajaxFlashcard');

Można również zastąpić znacznik span znacznikiem obrazu.

 7
Author: Umesh kumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-11 19:58:49

Oprócz ustawienia globalnych wartości domyślnych dla zdarzeń ajax, można ustawić zachowanie dla określonych elementów. Może wystarczy zmiana klasy?

$('#myForm').ajaxSend( function() {
    $(this).addClass('loading');
});
$('#myForm').ajaxComplete( function(){
    $(this).removeClass('loading');
});

Przykładowy CSS, aby ukryć #myForm za pomocą spinnera:

.loading {
    display: block;
    background: url(spinner.gif) no-repeat center middle;
    width: 124px;
    height: 124px;
    margin: 0 auto;
}
/* Hide all the children of the 'loading' element */
.loading * {
    display: none;  
}
 6
Author: LeeGee,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-02-15 16:01:10
$('#loading-image').html('<img src="/images/ajax-loader.gif"> Sending...');

        $.ajax({
            url:  uri,
            cache: false,
            success: function(){
                $('#loading-image').html('');           
            },

           error:   function(jqXHR, textStatus, errorThrown) {
            var text =  "Error has occured when submitting the job: "+jqXHR.status+ " Contact IT dept";
           $('#loading-image').html('<span style="color:red">'+text +'  </span>');

            }
        });
 4
Author: Izabela Skibinska,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-11 17:17:25

Użyłem poniższego okna dialogowego jQuery UI. (Może działa z innymi wywołaniami ajax?)

$('<div><img src="/i/loading.gif" id="loading" /></div>').load('/ajax.html').dialog({
    height: 300,
    width: 600,
    title: 'Wait for it...'
});

Zawiera animowany ładujący gif, dopóki jego zawartość nie zostanie zastąpiona po zakończeniu wywołania ajax.

 2
Author: Quinn Comendant,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-12-02 17:55:44

To jest najlepszy sposób dla mnie:

JQuery :

$(document).ajaxStart(function() {
  $(".loading").show();
});

$(document).ajaxStop(function() {
  $(".loading").hide();
});

Kawa :

  $(document).ajaxStart ->
    $(".loading").show()

  $(document).ajaxStop ->
    $(".loading").hide()

Docs: ajaxStart, ajaxStop

 2
Author: Fred K,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-11-11 15:48:22

JavaScript

$.listen('click', '#captcha', function() {
    $('#captcha-block').html('<div id="loading" style="width: 70px; height: 40px; display: inline-block;" />');
    $.get("/captcha/new", null, function(data) {
        $('#captcha-block').html(data);
    }); 
    return false;
});

CSS

#loading { background: url(/image/loading.gif) no-repeat center; }
 2
Author: Peter Mortensen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-11 19:58:05

Zauważ, że musisz używać wywołań asynchronicznych, aby Spinnery działały (przynajmniej to spowodowało, że moje nie pokazywało się dopiero po wywołaniu ajax, a następnie szybko zniknęło po zakończeniu połączenia i usunięciu spinnera).

$.ajax({
        url: requestUrl,
        data: data,
        dataType: 'JSON',
        processData: false,
        type: requestMethod,
        async: true,                         <<<<<<------ set async to true
        accepts: 'application/json',
        contentType: 'application/json',
        success: function (restResponse) {
            // something here
        },
        error: function (restResponse) {
            // something here                
        }
    });
 2
Author: Shane Rowatt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-23 07:20:30

Jest to bardzo prosta i inteligentna wtyczka do tego konkretnego celu: https://github.com/hekigan/is-loading

 2
Author: andcl,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-06 16:39:58

Robię to:

var preloaderdiv = '<div class="thumbs_preloader">Loading...</div>';
           $('#detail_thumbnails').html(preloaderdiv);
             $.ajax({
                        async:true,
                        url:'./Ajaxification/getRandomUser?top='+ $(sender).css('top') +'&lef='+ $(sender).css('left'),
                        success:function(data){
                            $('#detail_thumbnails').html(data);
                        }
             });
 1
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-09-29 12:46:35

Myślę, że masz rację. Ta metoda jest zbyt globalna...

Jednak-jest to dobra domyślna opcja, gdy wywołanie AJAX nie ma wpływu na samą stronę. (np. zapis w tle). ( zawsze możesz go wyłączyć dla określonego wywołania ajax, przekazując "global": false-zobacz dokumentację w jquery

Gdy wywołanie AJAX ma odświeżyć część strony, lubię, gdy moje" ładowanie " obrazów jest specyficzne dla odświeżonej sekcji. Chciałbym zobaczyć, która część jest odświeżona.

Wyobraź sobie, jak fajnie byłoby, gdybyś mógł po prostu napisać coś w stylu:

$("#component_to_refresh").ajax( { ... } ); 

I to pokazuje "ładowanie" w tej sekcji. Poniżej jest funkcja, którą napisałem, że obsługuje" ładowanie " wyświetlacz, jak również, ale jest to specyficzne dla obszaru, które są odświeżania w ajax.

Po pierwsze, pozwól, że pokażę Ci, jak go używać

<!-- assume you have this HTML and you would like to refresh 
      it / load the content with ajax -->

<span id="email" name="name" class="ajax-loading">
</span>

<!-- then you have the following javascript --> 

$(document).ready(function(){
     $("#email").ajax({'url':"/my/url", load:true, global:false});
 })

I to jest funkcja-podstawowy początek, który możesz ulepszyć, jak chcesz. jest bardzo elastyczny.

jQuery.fn.ajax = function(options)
{
    var $this = $(this);
    debugger;
    function invokeFunc(func, arguments)
    {
        if ( typeof(func) == "function")
        {
            func( arguments ) ;
        }
    }

    function _think( obj, think )
    {
        if ( think )
        {
            obj.html('<div class="loading" style="background: url(/public/images/loading_1.gif) no-repeat; display:inline-block; width:70px; height:30px; padding-left:25px;"> Loading ... </div>');
        }
        else
        {
            obj.find(".loading").hide();
        }
    }

    function makeMeThink( think )
    {
        if ( $this.is(".ajax-loading") )
        {
            _think($this,think);
        }
        else
        {
            _think($this, think);
        }
    }

    options = $.extend({}, options); // make options not null - ridiculous, but still.
    // read more about ajax events
    var newoptions = $.extend({
        beforeSend: function()
        {
            invokeFunc(options.beforeSend, null);
            makeMeThink(true);
        },

        complete: function()
        {
            invokeFunc(options.complete);
            makeMeThink(false);
        },
        success:function(result)
        {
            invokeFunc(options.success);
            if ( options.load )
            {
                $this.html(result);
            }
        }

    }, options);

    $.ajax(newoptions);
};
 1
Author: guy mograbi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-07-12 15:12:40

Jeśli nie chcesz pisać własnego kodu, istnieje również wiele wtyczek, które właśnie to robią:

 1
Author: keithhackbarth,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-11 19:59:51

Jeśli planujesz używać loadera za każdym razem, gdy składasz żądanie serwera, możesz użyć następującego wzoru.

 jTarget.ajaxloader(); // (re)start the loader
 $.post('/libs/jajaxloader/demo/service/service.php', function (content) {
     jTarget.append(content); // or do something with the content
 })
 .always(function () {
     jTarget.ajaxloader("stop");
 });

Ten kod w szczególności wykorzystuje wtyczkę jajaxloader (którą właśnie stworzyłem)

Https://github.com/lingtalfi/JAjaxLoader/

 1
Author: ling,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-03 21:09:55

Zawsze możesz użyć Block UI jQuery plugin który robi wszystko za Ciebie, a nawet blokuje stronę dowolnego wejścia podczas ładowania ajax. W przypadku, gdy wtyczka wydaje się nie działać, można przeczytać o właściwym sposobie korzystania z niego w tej odpowiedzi.Zobacz też

 0
Author: SamyCode,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-15 16:10:58

Mój kod ajax wygląda tak, w efekcie właśnie skomentowałem linię async: false i pojawia się spinner.

$.ajax({
        url: "@Url.Action("MyJsonAction", "Home")",
        type: "POST",
        dataType: "json",
        data: {parameter:variable},
        //async: false, 

        error: function () {
        },

        success: function (data) {
          if (Object.keys(data).length > 0) {
          //use data 
          }
          $('#ajaxspinner').hide();
        }
      });

Pokazuję spinner w funkcji przed kodem ajax:

$("#MyDropDownID").change(function () {
        $('#ajaxspinner').show();

Dla Html, użyłem Font awesome class:

<i id="ajaxspinner" class="fas fa-spinner fa-spin fa-3x fa-fw" style="display:none"></i>

Mam nadzieję, że to komuś pomoże.
 0
Author: Jaggan_j,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-04 10:44:43