javascript-如何使用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>
Xavi asked 2020-01-14T03:10:48Z
9个解决方案
66 votes

该链接描述了如何向xhr对象jquery添加进度事件侦听器。

$.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
    }
});
Prateek answered 2020-01-14T03:10:56Z
21 votes
<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");
    });
Suvash sarker answered 2020-01-14T03:11:16Z
13 votes

基本上,您需要加载图像从此处下载免费的图像[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正文上

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

可能对您有帮助

Anish answered 2020-01-14T03:11:44Z
6 votes

这是一个在Razor中使用MVC和Javascript的示例。 第一个函数通过控制器上的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');
        });
chuck answered 2020-01-14T03:12:13Z
5 votes

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

Rohit Dodiya answered 2020-01-14T03:13:34Z
4 votes

经过大量搜索以显示进度条的方式来做出最优雅的充电后,找不到适合我目的的任何方式。 检查请求的实际状态显示demaziado复杂,有时片段然后不起作用创建了一个非常简单的方法,但是它为我提供了(或几乎)寻求的经验,请遵循以下代码:

$.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);
    }
});
Gabriel Glauber answered 2020-01-14T03:13:54Z
2 votes

我知道已经为该解决方案编写了很多答案,但是我想展示另一种javascript方法(取决于JQuery),在该方法中,您只需要仅包含一个JS文件,而无需在代码中依赖CSS或Gif图片, 请注意在Ajax Request期间发生的所有与进度条相关的动画。您需要像这样简单地传递javascript函数

var objGlobalEvent = new RegisterGlobalEvents(true, "");

Preview of Fiddle Loader Type

这是代码的工作小提琴。 [https://jsfiddle.net/vibs2006/c7wukc41/3/]

vibs2006 answered 2020-01-14T03:14:19Z
1 votes

我是这样做的

的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");
    }); 
});
Developer answered 2020-01-14T03:14:48Z
0 votes

试试这个可能对你有帮助

 $.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
  });
Ali answered 2020-01-14T03:15:07Z
translate from https://stackoverflow.com:/questions/20095002/how-to-show-progress-bar-while-loading-using-ajax