【问题标题】:how to implement progress bar based on ajax response如何实现基于ajax响应的进度条
【发布时间】:2015-07-12 05:31:56
【问题描述】:

我已尝试基于来自服务器端 (PHP) 的 ajax 响应来实现进度条。但我无法识别进度条计算,例如如何计算通过 ajax 提交表单的请求和响应之间的进度条时间。

<script>
$('.uploadProject').on('submit',function(e){
      e.preventDefault();
    //ray.ajax();
    var formData = new FormData($(this)[0]);
    progress(80, $('#progressBar'));
    $.ajax({
        url: "ajax/submitted_project_action.php",
        type: "POST",
        data: formData,
        async: false,
        success: function (data) {
            if(data==1){
                window.location.href="submitted_project.php?success";
            }else{
                window.location.href="submitted_project.php?error";
            }
        },
        cache: false,
        contentType: false,
        processData: false
    });


})

 <script>
 function progress(percent, $element) {
var progressBarWidth = percent * $element.width() / 100;
$element.find('div').animate({ width: progressBarWidth },500).html(percent + "%&nbsp;");
}
</script>

我的 HTML 代码

   <style>
        #progressBar {
width: 400px;
height: 22px;
border: 1px solid #111;
background-color: #292929;
}
#progressBar div {
height: 100%;
color: #fff;
text-align: right;
line-height: 22px; /* same as #progressBar height if we want text middle aligned */
width: 0;
background-color: #0099ff;
}
        </style>

         <div id="progressBar"><div></div></div>

【问题讨论】:

标签: php jquery ajax progress-bar


【解决方案1】:

最好的方法是listen to the "progress" event listener

例子:

$.ajax({
  type: 'POST', // GET/POST
  url: "/", // Some URL
  data: {}, // Misc data
  beforeSend: function(XMLHttpRequest) // Do the following before sending the request
  {
    //Upload progress
    XMLHttpRequest.upload.addEventListener("progress", function(event) // Add a "progress" listener.
    {
      if (evt.lengthComputable) 
      {  
        var percentComplete = (event.loaded / event.total) * 100;
        // You can use this data for your progress bar.
      }
    }, false); 
  },
  success: function(data)
  {
  // Here, you can make your progress bar green or something.
  }
});

【讨论】:

  • 运行上述代码时出现错误。 TypeError: XMLHttpRequest.upload 未定义
  • 你需要先定义它。
猜你喜欢
  • 1970-01-01
  • 2011-10-20
  • 1970-01-01
  • 1970-01-01
  • 2021-11-19
  • 1970-01-01
  • 2022-01-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多