如何在加载时显示进度条,使用ajax

     2023-02-22     250

关键词:

【中文标题】如何在加载时显示进度条,使用ajax【英文标题】:How to show progress bar while loading, using ajax 【发布时间】:2013-12-04 09:21:58 【问题描述】:

我有一个下拉框。当用户从下拉框中选择一个值时,它会执行查询以从数据库中检索数据,并使用 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>

【问题讨论】:

您不能使用进度条,因为数据库查询在完成之前不会返回任何内容。不过你可以有一个简单的加载动画。 感谢您的回复,您能指导我如何操作吗? 您可以使用ajaxstart 和ajaxstop 事件显示/隐藏包含动画的div。 您是否对 AJAX 请求有超时 - 或者大致了解请求最多可以多长时间? 【参考方案1】:

link 描述了如何使用 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
    
);

【讨论】:

这不再适用于 jQuery 1.9.3+。它在完成 1% 时进入事件侦听器,并且再也不会点击它。有什么想法吗? 您可以尝试使用 jquery 的加载程序超时。在 ajaxstart 上设置计时器并在 ajaxStop 上停止 它不工作。 xhr.upload.addEventListener 中的upload 是什么? 在将percentComplete 乘以 100 后,这对我有用。感谢您的解决方案。 var percentComplete = evt.loaded / evt.total;实际上是:var percentComplete = (evt.loaded / evt.total) * 100;【参考方案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");
    );

【讨论】:

如果在同一页面上运行其他 ajax 请求怎么办?我们如何对特定的 ajax 请求执行此操作。 @prime,将其分配给一个变量。 @Suvash 他要求进度条显示请求的实时完成进度,而不是您回答的加载程序。【参考方案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正文

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

这可能对你有帮助

【讨论】:

+1 非常简单直接的 Ajax 请求。为我工作。没有使用下载图片选项,因为我正在为通用应用程序使用进度控制。 简单。没有麻烦,一条线的解决方案。【参考方案4】:

这是一个适用于我在 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');
        );

【讨论】:

【参考方案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"    style="position: fixed; top: 50%; left: 50%;" />
</div>

【讨论】:

【参考方案6】:

经过大量搜索以显示进度条以进行最优雅的充电的方法后,找不到任何可以满足我的目的的方法。检查请求的实际状态显示 demaziado 复杂,有时 sn-ps 不工作然后创建了一个非常简单的方法,但它给了我寻求(或几乎)的经验,遵循代码:

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

【讨论】:

【参考方案7】:

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

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

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

【讨论】:

@searchengine27 此屏幕截图不适用于阅读代码。发布它是为了让您了解加载器的图形预览。如果你能注意到,那么我还包含了代码小提琴的链接,点击它你会得到整个代码。 这超过 400kb... 非常糟糕的解决方案。 @JuanFernandoz 如果大小有问题,那么您可以用您的外部 gif src 替换内联嵌入图像。【参考方案8】:

我是这样做的

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

【讨论】:

【参考方案9】:

试试这个可能对你有帮助

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

【讨论】:

与操作要求的不接近。他想在加载时显示进度,而不仅仅是加载 gif。【参考方案10】:

我一般用这种方式简单又好用

<input id="datainput" type="text">
<div id="result"></div>
<button id="examplebutton"></button>
<script>
    $("#examplebutton").click(function()
        let data=$("#datainput").val(); 
        $("#result").html("Please Wait..");  // it starts working when the button is clicked
        
        $.ajax(
            url:"../ajax/xyz.php",
            type:"POST",
            data:data:data,
            success:function(result)
            
                $("#result").html(result);  // When the data comes, the text will be deleted and the data will come.
            
        );
    );
</script>

【讨论】:

您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center。【参考方案11】:

这肯定会奏效。 来了……

function yourFunction()
    
    setTimeout(function()
        $('#loading').show();
        
        setTimeout(function()
            //your ajax code goes here...
            $('#loading').hide();           
        , 500);

    , 300);
    

您可以根据自己的要求将 css 设置为进度条。默认隐藏此 div。

<div id="loading">
    <img id="loading-image" src="img-src"  />
</div>

【讨论】:

发出 JSF Ajax 请求时显示加载进度

...gJSFAjaxrequest【发布时间】:2011-12-1409:58:27【问题描述】:如何在使用&lt;f:ajax&gt;发出请求时显示一些加载消息?【问题讨论】:【参考方案1】:如果您还没有使用第三方组件库,该库可能已经有现成的组件,例如PrimeFaces和... 查看详情

切换活动时显示进度条

...2021-07-2120:17:16【问题描述】:请指导我在活动之间切换时如何显示进度条。在我的第二个活动中,有很多计算和编码视图,这会导致预期的打开延迟。但我想以百分比显示加载进度附加屏幕截图的更多详细信息screenshot【问题讨... 查看详情

加载 Activity 时显示进度条

】加载Activity时显示进度条【英文标题】:ShowaprogressbarwhenanActivityisloading【发布时间】:2011-06-1912:08:42【问题描述】:我有一个ListActivity,它会根据列表选择启动另一个Activity。这第二个Activity需要从互联网加载相当多的数据,因... 查看详情

android中webview怎么实现网页加载时显示加载进度

方法一:可以在WebView上面放一个进度条,加载webView时显示出来,然后webView里面有加载回调的方法,判断状态码如果是200则隐藏即可。方法二:在webview里面加进度条参考技术A可以在第一次加载进度达到百分之百时重新加载里一... 查看详情

php脚本通过ajax运行时显示进度条

】php脚本通过ajax运行时显示进度条【英文标题】:Displayprogressbarwhilethephpscriptisrunningthroughajax【发布时间】:2016-03-1914:22:39【问题描述】:我有一个通过ajax向服务器提交值的表单。<form><inputid="titlee"name="titlee"><inputtype=... 查看详情

如何在页面加载时显示 ajax 加载 gif 动画?

】如何在页面加载时显示ajax加载gif动画?【英文标题】:Howtoshowajaxloadinggifanimationwhilethepageisloading?【发布时间】:2010-11-2106:33:54【问题描述】:我尝试在我的网站中实现AJAX。当点击divchangepass的内容时,它应该加载changepass.templat... 查看详情

如何在python中将文件保存到excel时显示进度条?

】如何在python中将文件保存到excel时显示进度条?【英文标题】:Howtoshowprogressbarwhilesavingfiletoexcelinpython?【发布时间】:2020-06-0313:06:00【问题描述】:如果你能帮助我,不胜感激。将文件保存到Excel时,我无法显示进度条。我想... 查看详情

如何在android中将url加载到webview时显示进度?

】如何在android中将url加载到webview时显示进度?【英文标题】:howtodisplayprogresswhileloadingaurltowebviewinandroid?【发布时间】:2012-07-0213:38:44【问题描述】:我正在将url加载到webview中:WebViewwebview=(WebView)findViewById(R.id.webview);webview.loadUr... 查看详情

在 SFX 存档提取时显示进度条

】在SFX存档提取时显示进度条【英文标题】:ShowingaprogressbarwhileSFXarchiveisextracting【发布时间】:2010-05-1808:54:24【问题描述】:我正在使用C++和本机Win32API编写程序。我正在以静默模式从SFX存档EXE创建一个进程,没有向用户显示GUI... 查看详情

与 NSTimer 一起使用时显示刻度动画而不是平滑动画的进度条

...以下代码,但我得到进度条的刻度动画而不是平滑动画,如何使其平滑动画-(void)vie 查看详情

在 C# 中做一些工作时显示进度条?

】在C#中做一些工作时显示进度条?【英文标题】:DisplayprogressbarwhiledoingsomeworkinC#?【发布时间】:2010-12-2911:03:53【问题描述】:我想在做一些工作时显示一个进度条,但这会挂起UI并且进度条不会更新。我有一个带有ProgressBar的W... 查看详情

C++ - 使用 std::async 时显示进度条

】C++-使用std::async时显示进度条【英文标题】:C++-displayprogressbarwhenusingstd::async【发布时间】:2018-04-1810:44:50【问题描述】:所以我正在研究光线追踪器,为了减少渲染时间,我使用std::async独立进行像素计算。我使用了this教程,... 查看详情

执行 $.ajax 时显示加载图像

...发布时间】:2011-06-0818:08:10【问题描述】:我只是想知道如何显示表明异步请求正在运行的图像。我使用以下代码执行异步请求:$.ajax(url:uri,cache:false,success:function(html)$(\'.info\').append(html););有什么想法吗?【问题讨论 查看详情

当 shellexecute 命令在 MFC 中执行批处理文件时显示进度条

...状态为“进行中”并禁用对话框上的所有其他控件。我们如何在MFC中 查看详情

在javascript-ajax中提交表单时如何显示进度条

】在javascript-ajax中提交表单时如何显示进度条【英文标题】:Howtoshowtheprogressbarwhensubmittingtheforminjavascript-ajax【发布时间】:2021-06-1819:18:10【问题描述】:我已经做了进度条和一切。但是当我选择文件上传时出现问题,这意味着... 查看详情

axios ajax,发出ajax请求时显示加载

】axiosajax,发出ajax请求时显示加载【英文标题】:Axiosajax,showloadingwhenmakingajaxrequest【发布时间】:2018-11-1823:44:26【问题描述】:我目前正在构建一个vue应用程序,并且正在使用axios。我有一个加载图标,我会在每次调用之前显示... 查看详情

在文档正文尚未加载时显示加载器

...【发布时间】:2019-11-0920:41:36【问题描述】:有一些答案如何在加载元素时显示加载器。我的问题不一样。我想在加载文档正文之前显示加载器。我有ajax调用varurl=window.location.origin+"/test.html";showLoader();$$.ajax(type:"GE 查看详情

MATLAB:保存文件时显示进度条?

】MATLAB:保存文件时显示进度条?【英文标题】:MATLAB:Showaprogressbarwhensavingfile?【发布时间】:2016-11-0402:35:45【问题描述】:我有一个MATLABGUI(在GUIDE中开发),我让用户可以选择保存某些数据结构变量(作为.mat文件)。但是,... 查看详情