7

is it possible to have a progress bar measuring the jQuery.get() progress?

4

2 回答 2

7

This is not given out-of-the-box in the current version of jQuery, but still possible with little effort.

You should listen to the progress event of the XMLHttpRequest which jQuery gives you access to. An example from Dave Bond's blog:

$.ajax(
{
  type: 'POST', // 'POST' here so that _upload_ progress _also_ makes sense; 
                // Change to 'GET' if you need. 
  url: "/", data: {}, 
  beforeSend: function(XMLHttpRequest)
  {
    //Upload progress
    XMLHttpRequest.upload.addEventListener("progress", function(evt){
      if (evt.lengthComputable) {  
        var percentComplete = evt.loaded / evt.total;
        //Do something with upload progress
      }
    }, false); 

    //Download progress
    XMLHttpRequest.addEventListener("progress", function(evt){
      if (evt.lengthComputable) {  
        var percentComplete = evt.loaded / evt.total;
        //Do something with download progress
      }
    }, false); 
  },

  success: function(data){
    // successful completion handler
  }
});

Here the link to the docs on XMLHttpRequest's progress event.

You may also want to take a look a the jquery.ajax-progress plugin to avoid doing it yourself.


Notes:

  • Some older browsers may not support the progress event.

  • To calculate download progress, you must know the size of the resource to be downloaded, i.e. the server must send the Content-length HTTP header. If size is not known, then it's not possible to calculate the progress. This is what the lengthComputable property of the progress event is for.

于 2013-08-31T06:53:14.410 回答
-3

If you are able to divide up the task that the server is handling into chunks of processing you can make a servers response call another $.get() and update a progress bar that way.

function get_chunk(chunk_number, max_chunks){
    $.get('eg.php?chunk=' + chunk_number, function(){
        chunk_number++;
        if(chunk_number < max_chunks){
            get_chunk(chunk_number, max_chunks)
        }
        update_status_bar(chunk_number, max_chunks);
    }
}

Otherwise you will have to look into a web application model like Comet which uses server side pushing where the client does not have to make a request in order for data to be sent to the client

于 2013-08-31T06:37:06.223 回答