Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

javascript - Possible to calculate how much data been loaded with AJAX?

I've been busy with some AJAX code. I want to calculate how much data has been loaded and I want to display it with percents.

All my preloaded info is inside "feedback". Can I calculate how much DATA it contains (in bytes) and can I also view the progress? Like when it has loaded: 10kb, 20kb, 30kb etc

My code:

function calc(page)
    {
    $('#pageLoad h2').animate({ marginTop : '0px'}, 200);
        $.ajax(
        {
            url:            './pages/page.php',
            type:           'POST',
            data:           'page='+page,
            success:        function( feedback )
            {
                $('#content').html( feedback );
            }                               

        });
    };

Sorry for my poor english.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It is possible. XHRs have a progress event. The only problem is accessing the XHR object - unfortunately beforeSend only receives the jqXHR object and not the underlying XHR object. It is also not accessible as a property of the wrapper. You can however hook into the creation process of the XHR object by adding the following option to $.ajax():

xhr: function () {
    var xhr = $.ajaxSettings.xhr(); // call the original function
    xhr.addEventListener('progress', function (e) {
        if (e.lengthComputable) {
            var percentComplete = e.loaded / e.total;
            // Do something with download progress
        }
    }, false);
    return xhr;
}

Here's my initial solution. It is extremely hard to combine with jQuery since you can't easily hook into the onreadystatechange handler and cannot safely replace it after it has been set:

You need to add a custom onreadystatechange handler. When the readyState of the XHR object becomes 2 (*HEADERS_RECEIVED*) you can access the Content-Length header to get the total size and then wait for the event to fire with xhr.readyState == 3 (LOADING).

Then you can calculate the progress by looking at xhr.responseText.length.
However, this will only fire once. So you need to start a timer (using setInterval()) which will check the ready state and response size e.g. every 100 msecs. As soon as the request finishes you stop the interval again using clearInterval().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...