DIV CSS 佈局教程網

jQuery 搭配 XMLHttpRequest 實作檔案上傳進度條
編輯:JQuery入門技巧     

原理

XMLHttpRequest 的 upload 物件可綁定 onprogress 事件,用來取得上傳中的 loaded 與 total,進而計算百分比。jQuery 的 $.ajax 預設自行建立 xhr,因此可透過 ajaxSettings.xhr 提供自訂物件。

封裝進度監聽

var xhrOnProgress = function (fun) {
  xhrOnProgress.onprogress = fun;
  return function () {
    var xhr = $.ajaxSettings.xhr();
    if (typeof xhrOnProgress.onprogress === 'function' && xhr.upload) {
      xhr.upload.onprogress = xhrOnProgress.onprogress;
    }
    return xhr;
  };
};

使用方式

$.ajax({
  url: url,
  type: 'POST',
  xhr: xhrOnProgress(function (e) {
    var percent = e.loaded / e.total;
    console.log(percent);
  })
});
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved