8
$.ajax({
  xhr: function()
  {
    var xhr = new window.XMLHttpRequest();
    //Upload progress
    xhr.upload.addEventListener("progress", function(evt){
      if (evt.lengthComputable) {
        var percentComplete = evt.loaded / evt.total;
        //Do something with upload progress
        console.log(percentComplete);
      }
    }, false);
    //Download progress
    xhr.addEventListener("progress", function(evt){
      if (evt.lengthComputable) {
        var percentComplete = evt.loaded / evt.total;
        //Do something with download progress
        console.log(percentComplete);
        }
      }, false);
    return xhr;
  },
  type: 'POST',
  url: "/",
  data: {},
  success: function(data){
    //Do something success-ish
  }
});

这在 jQuery 1.5+ 上不起作用,因为 xhr 被 jqXHR 取代(即原始 XHR 的高级版本)。现在的问题是如何让它与 jqXHR 一起工作......有人知道怎么做吗?

4

3 回答 3

11

尝试这个

$.ajax({
    url: path,
    xhr: function () {
        var xhr = $.ajaxSettings.xhr();
        xhr.upload.onprogress = function (e) {
            if (e.lengthComputable) {
                console.log(e.loaded / e.total);
            }
        };
        return xhr;
    }
}).done(function (e) {

})
于 2014-03-17T17:26:19.207 回答
4

我制作了一个 jquery 插件来以简单的方式处理上传或下载进度事件。适用于任何 jquery ajax 方法,例如 $.ajax、$.get、$getJSON、$.post 等。您可以从此处下载:https ://github.com/cvelazquez/jquery.ajax.progress

var jqXHR = $.post('www.somedomain.com', {data:"real long data, o maybe a file upload"}, function(response){
    /* do anything on finish */
});

$(jqXHR).on('uploading', function(proxyEvent, event){
    if (event.lengthComputable) {
        // You can do anything here
        console.log("Uploaded " + parseInt( (event.loaded / event.total * 100), 10) + "%");
    }
});
于 2015-03-15T11:21:52.307 回答
1

搜索文档和其他问题,似乎有一个插件来监控 jquery ajax 进度:https ://github.com/hiddentao/jquery.ajaxprogress

于 2012-11-02T21:46:02.907 回答