获取 JQuery ajax 请求进度的最干净方法是什么? [英] What is the cleanest way to get the progress of JQuery ajax request?

查看:43
本文介绍了获取 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);

但我正在做一个使用 JQuery 下载 html 数据的 ajax 站点($.get()$.ajax()),我想知道哪个是获取请求进度的最佳方法,以便用一个小进度条显示它,但奇怪的是,我在 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 请求进度的最干净方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆