What is the cleanest way to get the progress of JQuery ajax request?(获取 JQuery ajax 请求进度的最干净的方法是什么?)
问题描述
在普通的javascript中非常简单:只需要将回调附加到{XMLHTTPRequest}.onprogress
In plain javascript is very simple: need just to attach the callback to {XMLHTTPRequest}.onprogress
var xhr = new XMLHttpRequest();
xhr.onprogress = function(e){
    if (e.lengthComputable)
        var percent = (e.loaded / e.total) * 100;
};
xhr.open('GET', 'http://www...', true);
xhr.onreadystatechange = function() {
    ...
};
xhr.send(null);
但我正在做一个 ajax 站点,它使用 JQuery($.get() 或 $.ajax())下载 html 数据,我想知道哪个是获取请求进度的最佳方法是用一点进度条显示它,但奇怪的是,我在 JQuery 文档中找不到任何有用的东西......
but I'm doing an ajax site that download html data with JQuery ($.get() or $.ajax()) and I was wondering which is the best way to get the progress of a request in order to display it with a little progress bar but curiously, I'm not finding anything usefull in JQuery documentation...
推荐答案
类似这样的 $.ajax (虽然只有 HTML5):
Something like this for $.ajax (HTML5 only though):
$.ajax({
    xhr: function() {
        var xhr = new window.XMLHttpRequest();
        xhr.upload.addEventListener("progress", function(evt) {
            if (evt.lengthComputable) {
                var percentComplete = evt.loaded / evt.total;
                //Do something with upload progress here
            }
       }, false);
       xhr.addEventListener("progress", function(evt) {
           if (evt.lengthComputable) {
               var percentComplete = evt.loaded / evt.total;
               //Do something with download progress
           }
       }, false);
       return xhr;
    },
    type: 'POST',
    url: "/",
    data: {},
    success: function(data){
        //Do something on success
    }
});
                        这篇关于获取 JQuery ajax 请求进度的最干净的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:获取 JQuery ajax 请求进度的最干净的方法是什么?
				
        
 
            
        基础教程推荐
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
 - 每次设置弹出窗口的焦点 2022-01-01
 - 如何使用 CSS 显示和隐藏 div? 2022-01-01
 - 如何在特定日期之前获取消息? 2022-01-01
 - Node.js 有没有好的索引/搜索引擎? 2022-01-01
 - jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
 - 什么是不使用 jQuery 的经验技术原因? 2022-01-01
 - WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
 - Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
 - 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				