Подтвердить что ты не робот

Как показать индикатор выполнения при загрузке, используя ajax

У меня есть раскрывающийся список. Когда пользователь выбирает значение из раскрывающегося списка, он выполняет запрос для извлечения данных из базы данных и показывает результаты в переднем конце с помощью ajax. Это занимает немного времени, поэтому за это время я хочу показать индикатор выполнения. Я искал, и я нашел множество руководств по созданию индикаторов выполнения для загрузки, но мне это не понравилось. Может ли кто-нибудь дать мне полезное руководство?

Мой код ajax:

<script>
$(function() {
    $("#client").on("change", function() {
      var clientid=$("#client").val();

        $.ajax({
            type:"post",
            url:"clientnetworkpricelist/yourfile.php",
            data:"title="+clientid,
            success:function(data){
             $("#result").html(data);
            }
        });

    });
});
</script>
4b9b3361

Ответ 1

Эта ссылка описывает, как вы можете добавить слушателя событий прогресса в объект jquery объекта xhr.

$.ajax({
    xhr: function() {
        var xhr = new window.XMLHttpRequest();

        // Upload progress
        xhr.upload.addEventListener("progress", function(evt){
            if (evt.lengthComputable) {
                var percentComplete = evt.loaded / evt.total;
                //Do something with upload progress
                console.log(percentComplete);
            }
       }, false);

       // Download progress
       xhr.addEventListener("progress", function(evt){
           if (evt.lengthComputable) {
               var percentComplete = evt.loaded / evt.total;
               // Do something with download progress
               console.log(percentComplete);
           }
       }, false);

       return xhr;
    },
    type: 'POST',
    url: "/",
    data: {},
    success: function(data){
        // Do something success-ish
    }
});

Ответ 2

<script>
$(function() {
    $("#client").on("change", function() {
      var clientid=$("#client").val();
     //show the loading div here
    $.ajax({
            type:"post",
            url:"clientnetworkpricelist/yourfile.php",
        data:"title="+clientid,
        success:function(data){
             $("#result").html(data);
          //hide the loading div here
        }
    }); 
    });
});
</script>

Или вы также можете это сделать:

$(document).ajaxStart(function() {
        // show loader on start
        $("#loader").css("display","block");
    }).ajaxSuccess(function() {
        // hide loader on success
        $("#loader").css("display","none");
    });

Ответ 3

В принципе, вам нужно загрузить изображение. Скачайте бесплатное приложение http://www.ajaxload.info/

$(function() {
    $("#client").on("change", function() {
      var clientid=$("#client").val();
      $('#loadingmessage').show();

    $.ajax({
            type:"post",
            url:"clientnetworkpricelist/yourfile.php",
        data:"title="+clientid,
        success:function(data){
             $('#loadingmessage').hide();
             $("#result").html(data);
        }
    }); 
    });
});

В html body

<div id='loadingmessage' style='display:none'>
       <img src='img/ajax-loader.gif'/>
</div>

Возможно, это может помочь вам

Ответ 4

Вот пример, который работает для меня с MVC и Javascript в Razor. Первая функция вызывает действие через ajax на моем контроллере и передает два параметра.

        function redirectToAction(var1, var2)
        {
            try{

                var url = '../actionnameinsamecontroller/' + routeId;

                $.ajax({
                    type: "GET",
                    url: url,
                    data: { param1: var1, param2: var2 },
                    dataType: 'html',
                    success: function(){
                    },
                    error: function(xhr, ajaxOptions, thrownError){
                        alert(error);
                    }
                });

            }
            catch(err)
            {
                alert(err.message);
            }
        }

Используйте ajaxStart, чтобы запустить код выполнения.

           $(document).ajaxStart(function(){
            try
            {
                // showing a modal
                $("#progressDialog").modal();

                var i = 0;
                var timeout = 750;

                (function progressbar()
                {
                    i++;
                    if(i < 1000)
                    {
                        // some code to make the progress bar move in a loop with a timeout to 
                        // control the speed of the bar
                        iterateProgressBar();
                        setTimeout(progressbar, timeout);
                    }
                }
                )();
            }
            catch(err)
            {
                alert(err.message);
            }
        });

Когда процесс завершает работу, индикатор выполнения

        $(document).ajaxStop(function(){
            // hide the progress bar
            $("#progressDialog").modal('hide');
        });

Ответ 5

$(document).ready(function () { 
 $(document).ajaxStart(function () {
        $('#wait').show();
    });
    $(document).ajaxStop(function () {
        $('#wait').hide();
    });
    $(document).ajaxError(function () {
        $('#wait').hide();
    });   
});
<div id="wait" style="display: none; width: 100%; height: 100%; top: 100px; left: 0px; position: fixed; z-index: 10000; text-align: center;">
            <img src="../images/loading_blue2.gif" width="45" height="45" alt="Loading..." style="position: fixed; top: 50%; left: 50%;" />
</div>

Ответ 6

попробуйте это, это может помочь вам

 $.ajax({
  type:"post",
            url:"clientnetworkpricelist/yourfile.php",
        data:"title="+clientid,
  beforeSend: function(  ) {
    // load your loading fiel here
  }
})
  .done(function( data ) {
    //hide your loading file here
  });

Ответ 7

Я сделал это так:

CSS

html {
    -webkit-transition: background-color 1s;
    transition: background-color 1s;
}
html, body {
    /* For the loading indicator to be vertically centered ensure */
    /* the html and body elements take up the full viewport */
    min-height: 100%;
}
html.loading {
    /* Replace #333 with the background-color of your choice */
    /* Replace loading.gif with the loading image of your choice */
    background: #333 url('/Images/loading.gif') no-repeat 50% 50%;

    /* Ensures that the transition only runs in one direction */
    -webkit-transition: background-color 0;
    transition: background-color 0;
}
body {
    -webkit-transition: opacity 1s ease-in;
    transition: opacity 1s ease-in;
}
html.loading body {
    /* Make the contents of the body opaque during loading */
    opacity: 0;

    /* Ensures that the transition only runs in one direction */
    -webkit-transition: opacity 0;
    transition: opacity 0;
}

JS

$(document).ready(function () {
   $(document).ajaxStart(function () {     
       $("html").addClass("loading");
    });
    $(document).ajaxStop(function () {        
        $("html").removeClass("loading");
    });
    $(document).ajaxError(function () {       
        $("html").removeClass("loading");
    }); 
});

Ответ 8

После долгих поисков, чтобы показать индикатор выполнения, просто для того, чтобы сделать самую элегантную зарядку, не удалось найти способ, который мог бы служить моей цели. Проверьте фактический статус запроса, показанный demaziado complex, и иногда отрывки, которые затем не сработали, создали очень простой способ, но он дает мне опыт поиска (или почти), следуя коду:

$.ajax({
    type : 'GET',
    url : url,
    dataType: 'html',
    timeout: 10000,
    beforeSend: function(){
        $('.my-box').html('<div class="progress"><div class="progress-bar progress-bar-success progress-bar-striped active" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"></div></div>');
        $('.progress-bar').animate({width: "30%"}, 100);
    },
    success: function(data){  
        if(data == 'Unauthorized.'){
            location.href = 'logout';
        }else{
            $('.progress-bar').animate({width: "100%"}, 100);
            setTimeout(function(){
                $('.progress-bar').css({width: "100%"});
                setTimeout(function(){
                    $('.my-box').html(data);
                }, 100);
            }, 500);
        }
    },
    error: function(request, status, err) {
        alert((status == "timeout") ? "Timeout" : "error: " + request + status + err);
    }
});