code

jQuery에서 로딩 스피너를 표시하는 방법은 무엇입니까?

starcafe 2023. 5. 28. 20:58
반응형

jQuery에서 로딩 스피너를 표시하는 방법은 무엇입니까?

프로토타입에서 "로딩..."을 표시할 수 있습니다.다음 코드가 있는 이미지:

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

function showLoad () {
    ...
}

jQuery에서 다음과 같은 방법으로 서버 페이지를 요소에 로드할 수 있습니다.

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

프로토타입에서와 같이 로드 스피너를 이 명령에 연결하려면 어떻게 해야 합니까?

몇 가지 방법이 있습니다.내가 선호하는 방법은 요소 자체의 ajaxStart/Stop 이벤트에 함수를 연결하는 것입니다.

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

Ajax Start/Stop 기능은 Ajax 호출을 수행할 때마다 실행됩니다.

업데이트: jQuery 1.8 기준으로 설명서에는 다음과 같이 나와 있습니다..ajaxStart/Stop만 야해합다니착에만 .document그러면 위의 스니펫이 다음으로 변환됩니다.

var $loading = $('#loadingDiv').hide();
$(document)
  .ajaxStart(function () {
    $loading.show();
  })
  .ajaxStop(function () {
    $loading.hide();
  });

사용하는 jQuery의 경우

jQuery.ajaxSetup({
  beforeSend: function() {
     $('#loader').show();
  },
  complete: function(){
     $('#loader').hide();
  },
  success: function() {}
});

jQuery'를 사용하시면 됩니다..ajax하고 옵션을 합니다.beforeSend그리고 로더 디브와 같은 것을 보여줄 수 있는 함수를 정의하고 성공 옵션에서 로더 디브를 숨길 수 있습니다.

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();
    }
});

Spinning Gif 이미지를 가질 수 있습니다.여기 당신의 색 구성에 따라 훌륭한 AJAX 로더 생성기인 웹사이트가 있습니다: http://ajaxload.info/

사중인경우를 .$.ajax()다음과 같은 것을 사용할 수 있습니다.

$.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'
});

설정 이름은 "보내기 전"이지만 jQuery 1.5부터 "보내기"은 요청 유형에 관계없이 호출됩니다..show()다음과 같은 경우 함수가 호출됩니다.type: 'GET'.

AJAX 호출 직전에 DOM에 애니메이션 이미지를 삽입하고 인라인 기능을 수행하여 제거할 수 있습니다...

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

이렇게 하면 이후 요청 시 동일한 프레임에서 애니메이션이 시작됩니다(중요한 경우).이전 버전의 IE에서는 애니메이션에 문제가 있을 수 있습니다.

행운을 빕니다.

$('#message').load('index.php?pg=ajaxFlashcard', null, showResponse);
showLoad();

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

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

로드 플러그인 사용: http://plugins.jquery.com/project/loading

$.loading.onAjax({img:'loading.gif'});

변형:메인 페이지의 왼쪽 상단에 ID="filename" 아이콘이 있습니다. 그러면 아약스가 작동할 때 스피너 gif가 위에(투명도로) 오버레이됩니다.

jQuery.ajaxSetup({
  beforeSend: function() {
     $('#logo').css('background', 'url(images/ajax-loader.gif) no-repeat')
  },
  complete: function(){
     $('#logo').css('background', 'none')
  },
  success: function() {}
});

저는 결국 원래 답변에 두 가지 변경 사항을 추가했습니다.

  1. 1 및 은 jQuery 1.8에만 .document따라서 일부 Ajax 요청만 필터링하기가 더 어려워집니다.
  2. agaxSendagaxComplete로 전환하면 스피너를 표시하기 전에 현재 agax 요청을 검사할 수 있습니다.

다음은 변경 후 코드입니다.

$(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();
    })

저도 이 답변에 기여하고 싶습니다.저는 jQuery에서 비슷한 것을 찾다가 결국 사용하게 되었습니다.

http://ajaxload.info/ 에서 로딩 스피너를 받았습니다.제 솔루션은 http://christierney.com/2011/03/23/global-ajax-loading-spinners/ 의 이 간단한 답변을 기반으로 합니다.

기본적으로 HTML 마크업과 CSS는 다음과 같습니다.

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

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

그런 다음 jQuery를 코드화하면 다음과 같습니다.

<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>

그것만큼 간단합니다 :)

나중에 Ajax 호출을 사용하여 내용을 로드할 태그에 로더 이미지를 할당하기만 하면 됩니다.

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

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

스팬 태그를 이미지 태그로 바꿀 수도 있습니다.

Ajax 이벤트에 대한 글로벌 기본값을 설정할 뿐만 아니라 특정 요소에 대한 동작도 설정할 수 있습니다.아마도 그들의 수업을 바꾸는 것만으로 충분할까요?

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

예: CSS, 스피너로 #myForm을 숨기려면:

.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;  
}

스피너가 작동하려면 비동기 호출을 사용해야 합니다(적어도 그것이 아약스 호출이 끝나고 스피너가 제거될 때까지 내 호출이 표시되지 않은 이유입니다).

$.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                
        }
    });
$('#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>');

            }
        });

플러그인은 특정 목적을 위한 매우 간단하고 스마트한 플러그인입니다. https://github.com/hekigan/is-loading

저는 jQuery UI Dialog에서 다음을 사용했습니다.(다른 Ajax 콜백과 함께 작동할 수도 있습니까?)

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

Ajax 호출이 완료될 때 내용이 교체될 때까지 에는 애니메이션 로딩 gif가 포함되어 있습니다.

이것이 저에게 가장 좋은 방법입니다.

jQuery:

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

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

커피:

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

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

문서: agaxStart, agaxStop

자바스크립트

$.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; }

사용자 작업을 수행합니다.

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);
                        }
             });

당신 말이 옳은 것 같군요.이 메서드는 너무 전역적입니다...

그러나 AJAX 호출이 페이지 자체에 영향을 미치지 않는 경우에는 좋은 기본값입니다.(예: 백그라운드 저장).( "global":false를 전달하여 특정 Ajax 호출에 대해 언제든지 끌 수 있습니다. jquery의 설명서를 참조하십시오.

AJAX 호출이 페이지의 일부를 새로 고치기 위한 것이라면, 저는 제 "로드" 이미지가 새로 고친 섹션에 특정되기를 원합니다.어떤 부분이 새로 고쳐지는지 보고 싶습니다.

단순히 다음과 같은 것을 쓸 수 있다면 얼마나 멋질지 상상해 보십시오.

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

이 섹션에 "로드"가 표시됩니다.아래는 제가 작성한 "로딩" 디스플레이도 처리하는 기능이지만 아약스에서 새로고침하는 영역에만 해당됩니다.

먼저 사용법을 알려드리겠습니다.

<!-- 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});
 })

이것이 바로 여러분이 원하는 대로 향상시킬 수 있는 기본적인 시작입니다.그것은 매우 유연합니다.

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);
};

자신만의 코드를 작성하고 싶지 않은 경우 다음과 같은 기능을 수행하는 플러그인도 많이 있습니다.

서버 요청을 할 때마다 로더를 사용할 계획인 경우 다음 패턴을 사용할 수 있습니다.

 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");
 });

특히 이 코드는 jajaxloader 플러그인(내가 방금 만든)을 사용합니다.

https://github.com/lingtalfi/JAjaxLoader/

제 아약스 코드는 이렇게 생겼습니다. 사실상, 저는 방금 비동기식으로 코멘트를 달았습니다. 거짓 라인과 스피너가 나타납니다.

$.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();
        }
      });

나는 아약스 코드 앞에 있는 함수 내의 스피너를 보여주고 있습니다.

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

HTML의 경우, 저는 폰트 어썸 클래스를 사용했습니다.

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

누군가에게 도움이 되길 바랍니다.

블록 UI jQuery 플러그인을 사용하면 언제든지 모든 작업을 수행할 수 있으며, Ajax가 로드되는 동안 입력 페이지를 차단할 수도 있습니다.플러그인이 작동하지 않는 경우 이 답변에서 올바른 사용 방법을 읽을 수 있습니다.이것을 확인해 보세요.

<script>
                $(window).on('beforeunload', function (e) {
                    $("#loader").show();
                });
                $(document).ready(function () {
                    $(window).load(function () {
                        $("#loader").hide();
                    });
                });
            </script>

<div id="loader">
                    <img src="../images/loader.png" 
                         style="width:90px;">
                </div>

언급URL : https://stackoverflow.com/questions/68485/how-to-show-loading-spinner-in-jquery

반응형