可以使用xhrFields将进度功能添加到jQuery.ajax()中吗?

前端之家收集整理的这篇文章主要介绍了可以使用xhrFields将进度功能添加到jQuery.ajax()中吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如我所建议的: https://gist.github.com/HenrikJoreteg/2502497,我正在尝试添加onprogress功能到我的jQuery.ajax()文件上传上传工作正常,进度事件正在触发,但不如预期的那样 – 而不是在某个时间间隔重复点火,当上传完成时,它只会触发一次。有没有办法指定进度刷新的频率?还是我试图做一些不能做的事情?这是我的代码
  1. $.ajax(
  2. {
  3. async: true,contentType: file.type,data: file,dataType: 'xml',processData: false,success: function(xml)
  4. {
  5. // Do stuff with the returned xml
  6. },type: 'post',url: '/fileuploader/' + file.name,xhrFields:
  7. {
  8. onprogress: function(progress)
  9. {
  10. var percentage = Math.floor((progress.total / progress.totalSize) * 100);
  11. console.log('progress',percentage);
  12. if (percentage === 100)
  13. {
  14. console.log('DONE!');
  15. }
  16. }
  17. }
  18. });

解决方法

简答:
不,你不能使用xhrFields做你想要的。

长答案:

XmlHttpRequest对象中有两个进度事件:

>响应进度(XmlHttpRequest.onprogress)
这是当浏览器从服务器下载数据时。
>请求进度(XmlHttpRequest.upload.onprogress)
这是当浏览器将数据发送到服务器时(包括POST参数,Cookie和文件)

在您的代码中,您正在使用响应进度事件,但您需要的是请求进度事件。这是你如何做的:

  1. $.ajax({
  2. async: true,success: function(xml){
  3. // Do stuff with the returned xml
  4. },xhr: function(){
  5. // get the native XmlHttpRequest object
  6. var xhr = $.ajaxSettings.xhr() ;
  7. // set the onprogress event handler
  8. xhr.upload.onprogress = function(evt){ console.log('progress',evt.loaded/evt.total*100) } ;
  9. // set the onload event handler
  10. xhr.upload.onload = function(){ console.log('DONE!') } ;
  11. // return the customized object
  12. return xhr ;
  13. }
  14. });

xhr选项参数必须是返回一个本机XmlHttpRequest对象以供jQuery使用的函数

猜你在找的jQuery相关文章