简体   繁体   English

通过xhr进行JQuery ajax进展

[英]JQuery ajax progress via xhr

I am trying to capture ajax request`s progress. 我正在尝试捕获ajax请求的进度。 I am following article from this link http://www.dave-bond.com/blog/2010/01/JQuery-ajax-progress-HMTL5/ . 我正在关注此链接中的文章http://www.dave-bond.com/blog/2010/01/JQuery-ajax-progress-HMTL5/

It is not working as expected. 它没有按预期工作。 Div with id progressCounter should have something in it with % as far as i understand it but nothing happens in my case. 具有id progressCounter的 div应该在其中包含%,据我所知,但在我的情况下没有任何反应。 Any Help ? 任何帮助?

It seems to me like if (evt.lengthComputable) { is not working in XHR 在我看来, if (evt.lengthComputable) {XHR不起作用

JSFIDDLE: http://jsfiddle.net/bababalcksheep/r86gM/ JSFIDDLE: http //jsfiddle.net/bababalcksheep/r86gM/

HTML: HTML:

<div id="progressCounter"></div><br>
<div id="loading">Loading</div><br>
<div id="data"></div>

JS: JS:

var progressElem = $('#progressCounter');
var URL = "https://api.github.com/users/mralexgray/repos";
$("#loading").hide();
// write something in #progressCounter , later will be changed to percentage
progressElem.text(URL);

$.ajax({
    type: 'GET',
    dataType: 'json',
    url: URL,
    cache: false,
    error: function (xhr, ajaxOptions, thrownError) {
        alert(xhr.responseText);
        alert(thrownError);
    },
    xhr: function () {
        var xhr = new window.XMLHttpRequest();
        //Download progress
        xhr.addEventListener("progress", function (evt) {
            if (evt.lengthComputable) {
                var percentComplete = evt.loaded / evt.total;
                progressElem.html(Math.round(percentComplete * 100) + "%");
            }
        }, false);
        return xhr;
    },
    beforeSend: function () {
        $('#loading').show();
    },
    complete: function () {
        $("#loading").hide();
    },
    success: function (json) {
        $("#data").html("data receieved");
    }
});

ProgressEvent.lengthComputable ProgressEvent.lengthComputable

The ProgressEvent.lengthComputable read-only property is a Boolean flag indicating if the resource concerned by the ProgressEvent has a length that can be calculated. ProgressEvent.lengthComputable只读属性是一个布尔标志,指示ProgressEvent所关注的资源是否具有可以计算的长度。 If not, the ProgressEvent.total property has no significant value. 如果不是,则ProgressEvent.total属性没有重要值。

So in your case if you debug a little , you will find evt.lengthComputable = false; 所以在你的情况下如果调试一点,你会发现evt.lengthComputable = false; so you can not trace the progress; 所以你无法追踪进展;

    xhr.addEventListener("progress", function (evt) {
        console.log(evt.lengthComputable); // false
        if (evt.lengthComputable) {
            var percentComplete = evt.loaded / evt.total;
            progressElem.html(Math.round(percentComplete * 100) + "%");
        }
    }, false);

DEMO DEMO


FYI FYI

If lengthComputable is false within the XMLHttpRequestProgressEvent , that means the server never sent a Content-Length header in the response. 如果XMLHttpRequestProgressEvent lengthComputable为false,则表示服务器从未在响应中发送Content-Length header

FOR PHP 对于PHP

if (evt.lengthComputable) { is not working in XHR, I did this and now it is working. if(evt.lengthComputable){在XHR中不起作用,我这样做了,现在它正在工作。

PHP: PHP:

$startTime = time(); 
//your code or 
sleep(10); 
$endTime = time() - $startTime; 
header('Content-Length: '.strlen($endTime));
$response['success'] = true;
echo json_encode($response);

Here is my HTML: 这是我的HTML:

<div class="progress">
<div id="bulk-action-progbar" class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="1" aria-valuemin="0" aria-valuemax="100" style="width:1%">                 
</div>
</div>

Ajax: 阿贾克斯:

var percentComplete = 1;
$.ajax({
    method: 'post',
    url: 'test.php',
    data:{'actionPerform':'actionPerform'},
    xhr: function(){
          var xhr = new window.XMLHttpRequest();
          //Upload progress, request sending to server
          xhr.upload.addEventListener("progress", function(evt){
            console.log("in Upload progress");
            console.log("Upload Done");
          }, false);
          //Download progress, waiting for response from server
          xhr.addEventListener("progress", function(e){
            console.log("in Download progress");
            if (e.lengthComputable) {
              //percentComplete = (e.loaded / e.total) * 100;
              percentComplete = parseInt( (e.loaded / e.total * 100), 10);
              console.log(percentComplete);
              $('#bulk-action-progbar').data("aria-valuenow",percentComplete);
              $('#bulk-action-progbar').css("width",percentComplete+'%');

            }
            else{
                 console.log("Length not computable.");
            }
          }, false);
          return xhr;
    },
    success: function (res) {
        //...
    }
});

A simple roundabout of handling this could be the following. 处理此问题的简单回合可能如下。

$(document)
    .ajaxStart(
        function() {

            $
                .blockUI({
                    message : '<img src="img/loadajax.gif" title="Loading..">Loading...',
                    css : {
                        padding : 20,
                        margin : 5,
                        width : '30%',
                        top : '40%',
                        left : '35%',
                        textAlign : 'center',
                        color : '#000',
                        border : 'none',
                        backgroundColor : '#fff',
                        cursor : 'wait'
                    }
                });
            });

$(document).ajaxStop(function() {
    $.unblockUI();
});

Just give the path of the GIF that you want to show in the image src. 只需给出要在图像src中显示的GIF路径。 Add this code at the onload of your page or common layout/jsp or header file to run everywhere for all ajax calls 在页面的onload或公共布局/ jsp或头文件中添加此代码,以便在所有ajax调用的任何位置运行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM