[javascript] $ .ajax가 수행되는 동안 로딩 이미지 표시

비동기 요청이 실행 중임을 나타내는 이미지를 표시하는 방법이 궁금합니다. 다음 코드를 사용하여 비동기 요청을 수행합니다.

$.ajax({
  url: uri,
  cache: false,
  success: function(html){
    $('.info').append(html);
  }
});

어떤 아이디어?



답변

물론 요청하기 전에 표시하고 완료 한 후에 숨길 수 있습니다.

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

나는 일반적으로 모든 ajax 이벤트에 대해 표시되는 방식으로 전역 ajaxStart 및 ajaxStop 이벤트에 바인딩하는보다 일반적인 솔루션을 선호합니다.

$('#loading-image').bind('ajaxStart', function(){
    $(this).show();
}).bind('ajaxStop', function(){
    $(this).hide();
});


답변

ajax 객체의 beforeSend 및 완전한 기능을 사용하십시오. 모든 동작이 단일 개체에 캡슐화되도록 beforeSend 내부의 gif를 표시하는 것이 좋습니다. 성공 기능을 사용하여 gif를 숨기는 데주의하십시오. 요청이 실패해도 gif를 숨기고 싶을 것입니다. 이를 위해 Complete 기능을 사용하십시오. 다음과 같이 표시됩니다.

$.ajax({
    url: uri,
    cache: false,
    beforeSend: function(){
        $('#image').show();
    },
    complete: function(){
        $('#image').hide();
    },
    success: function(html){
       $('.info').append(html);
    }
});


답변

HTML 코드 :

<div class="ajax-loader">
  <img src="{{ url('guest/images/ajax-loader.gif') }}" class="img-responsive" />
</div>

CSS 코드 :

.ajax-loader {
  visibility: hidden;
  background-color: rgba(255,255,255,0.7);
  position: absolute;
  z-index: +100 !important;
  width: 100%;
  height:100%;
}

.ajax-loader img {
  position: relative;
  top:50%;
  left:50%;
}

JQUERY 코드 :

$.ajax({
  type:'POST',
  beforeSend: function(){
    $('.ajax-loader').css("visibility", "visible");
  },
  url:'/quantityPlus',
  data: {
   'productId':p1,
   'quantity':p2,
   'productPrice':p3},
   success:function(data){
     $('#'+p1+'value').text(data.newProductQuantity);
     $('#'+p1+'amount').text("₹ "+data.productAmount);
     $('#totalUnits').text(data.newNoOfUnits);
     $('#totalAmount').text("₹ "+data.newTotalAmount);
  },
  complete: function(){
    $('.ajax-loader').css("visibility", "hidden");
  }
});

}


답변

사람들이 일반적으로 ajax 호출 중에 표시하는 “이미지”는 애니메이션 GIF입니다. ajax 요청의 완료율을 확인할 수있는 방법이 없기 때문에 사용되는 애니메이션 GIF는 불확정 스피너입니다. 이것은 다양한 크기의 원의 공처럼 계속 반복되는 이미지입니다. 사용자 정의 불확정 스피너를 만드는 좋은 사이트는 http://ajaxload.info/입니다.


답변

$ .ajax 호출이 많은 경우 이것이 더 나을 것이라고 생각합니다.

$(document).ajaxSend(function(){
    $(AnyElementYouWantToShowOnAjaxSend).fadeIn(250);
});
$(document).ajaxComplete(function(){
    $(AnyElementYouWantToShowOnAjaxSend).fadeOut(250);
});

노트:

CSS를 사용하는 경우. ajax가 백엔드 코드에서 데이터를 가져 오는 동안 표시하려는 요소는 다음과 같아야합니다.

AnyElementYouWantToShowOnAjaxSend {
    position: fixed;
    top: 0;
    left: 0;
    height: 100vh; /* to make it responsive */
    width: 100vw; /* to make it responsive */
    overflow: hidden; /*to remove scrollbars */
    z-index: 99999; /*to make it appear on topmost part of the page */
    display: none; /*to make it visible only on fadeIn() function */
}


답변

나는 항상 BlockUI플러그인을 좋아했습니다 : http://jquery.malsup.com/block/

Ajax 요청이 실행되는 동안 페이지의 특정 요소 또는 전체 페이지를 차단할 수 있습니다.


답변

호출하기 전에 로딩 이미지를 div / span 어딘가에 삽입 한 다음 성공 함수에서 해당 이미지를 제거합니다. 또는 다음과 같은 로딩과 같은 CSS 클래스를 설정할 수 있습니다.

.loading
{
    width: 16px;
    height: 16px;
    background:transparent url('loading.gif') no-repeat 0 0;
    font-size: 0px;
    display: inline-block;
}

그런 다음이 클래스를 span / div에 할당하고 success 함수에서 지 웁니다.