문제

~ 안에 원기 다음 코드를 사용하여 "로드 중..." 이미지를 표시할 수 있습니다.

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

function showLoad () {
    ...
}

~ 안에 jQuery, 다음을 사용하여 서버 페이지를 요소에 로드할 수 있습니다.

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

하지만 Prototype에서 했던 것처럼 이 명령에 로딩 스피너를 어떻게 연결합니까?

도움이 되었습니까?

해결책

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

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

ajaxStart/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 로더 div와 같은 것을 표시할 수 있는 함수를 정의하고 성공 옵션에서 해당 로더 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();
    }
});

Spinning Gif 이미지를 가질 수 있습니다.다음은 귀하의 색 구성표에 따른 훌륭한 AJAX 로더 생성기인 웹사이트입니다. http://ajaxload.info/

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

당신이 사용하는 경우 $.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'
    });  

로딩 플러그인을 사용하세요: http://plugins.jquery.com/project/loading

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

변종:메인 페이지 왼쪽 상단에 id="logo" 아이콘이 있습니다.Ajax가 작동 중일 때 스피너 gif가 맨 위에 투명도와 함께 오버레이됩니다.

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

나는 두 가지 변경 사항으로 끝났습니다. 원래 답장.

  1. jQuery 1.8부터 ajaxStart와 ajaxStop은 다음에만 연결되어야 합니다. document.이로 인해 Ajax 요청 중 일부만 필터링하기가 더 어려워졌습니다.정말...
  2. 다음으로 전환 중 아약스보내기 그리고 아약스완료 스피너를 표시하기 전에 현재 Ajax 요청을 조사할 수 있습니다.

다음은 이러한 변경 후의 코드입니다.

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

스피너를 사용하여 #myForm을 숨기는 CSS 예:

.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 호출이 끝날 때까지 표시되지 않고 호출이 완료되면 신속하게 사라지고 스피너를 제거한 이유입니다).

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

            }
        });

jQuery UI 대화 상자에서 다음을 사용했습니다.(어쩌면 다른 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()

문서: 아약스시작, 아약스중지

자바스크립트

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

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

나는 이것을한다:

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 호출에 대해 언제든지 끌 수 있습니다. 문서를 참조하세요. 제이쿼리

AJAX 호출이 페이지의 일부를 새로 고치려는 경우, 새로 고친 섹션에만 "로딩" 이미지를 적용하는 것이 좋습니다.어떤 부분이 새로워졌는지 보고 싶습니다.

다음과 같이 간단하게 작성할 수 있다면 얼마나 멋질지 상상해 보십시오.

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

그러면 이 섹션에 "로드 중"이 표시됩니다.아래는 "로딩" 표시도 처리하는 내가 작성한 함수이지만 이는 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 코드는 다음과 같습니다. 실제로 방금 async를 주석 처리했습니다.잘못된 선과 스피너가 나타납니다.

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

Ajax 코드 앞에 함수 내에서 스피너를 표시하고 있습니다.

$("#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가 로드되는 동안 입력 페이지를 차단하기도 합니다.플러그인이 작동하지 않는 것 같으면 올바른 사용 방법을 읽어보세요. 이 답변에서. 확인 해봐.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top