How to get the current percentage of a download?

8

I want to get the percentage value of an ajax request from an external server. How to do?

$("#uptade_space_disk").click(function(){
     var url = "/calcular-espaco-em-disco"
     jQuery.ajax({
        url: url,
        dataType: 'script', 
        beforeSend: function() {
            $("#loader").show();
            $("#uptade_space_disk").hide();
        },                                      
        success: function() {
        },
        error: function() {
        }
    });
})
    
asked by anonymous 18.02.2014 / 16:15

1 answer

5

What you are looking for is a progress event, meaning it is updated as the download is processed. I've tailored your this answer code:

$("#uptade_space_disk").click(function(){
  var url = "/calcular-espaco-em-disco"
  $.ajax({
    url: url,
    dataType: 'script', 
    beforeSend: function () {
      $("#loader").show();
      $("#uptade_space_disk").hide();
    },                                      
    success: function () {},
    error: function () {},
    xhr: function () {
      // pega o objeto XmlHttpRequest que o jQuery está usando
      var xhr = $.ajaxSettings.xhr() ;
      // vincula a função ao evento
      xhr.onprogress = function(evt){
        $("#loader").text(Math.round(evt.loaded*100/evt.total) + '%');
      };
      // retorna o objeto para o jQuery
      return xhr;
    }
  });
});
    
18.02.2014 / 16:30