如何使用jquery监视ajax请求的进度响应

问题描述 投票:1回答:1

如何使用jquery监视ajax请求的进度响应

我调用一个API,在服务器上执行多次查找。一次调用可以导致5-10次查找。每次完成查找时,API都会在GET响应中附加一个字符串。完成所有查找后,将关闭连接。

我希望有一个在进度时触发的回调,并且最好找到一种在每次完成查找时解析服务器进度响应(访问数据)的方法。

我的问题是从不调用进程回调。

到目前为止这是我的代码。我试图修补xmlHttpRequest对象并扩展jquery的ajax方法。

(function addXhrProgressEvent($) {
    var originalXhr = $.ajaxSettings.xhr;
    $.ajaxSetup({
        xhr : function() {
            var req = originalXhr(), that = this;
            if (req) {
                if ( typeof req.addEventListener == "function" && that.progress !== undefined) {
                    req.addEventListener("progress", function(evt) {
                        that.progress(evt);
                    }, false);
                }
                if ( typeof req.upload == "object" && that.progressUpload !== undefined) {
                    req.upload.addEventListener("progress", function(evt) {
                        that.progressUpload(evt);
                    }, false);
                }
            }
            return req;
        }
    });
})(jQuery); 

$('#update').on('click', function(e) {
    e.preventDefault();

    var json = $.ajax({
        headers : {
            'Authorization' : "Basic " + btoa("abced:becd")
        },
        url : "http://123.123.123.123:5487/api/v1/check/" + $(this).attr('data-key'),
        type : "GET",
        crossDomain : true,
        dataType : "text",
        async : false,
        progress : function(evt) {
            /*this does not fire*/
            alert('callback fired!');
            /*this does not fire*/
            if (evt.lengthComputable) {
                console.log("Loaded " + parseInt((evt.loaded / evt.total * 100), 10) + "%");
            } else {
                console.log("Length not computable.");
            }
        },
        success : function(data, textStatus, jqXHR) {

        },
        error : function(jqXHR, textStatus, errorThrown) {

        }
    });

});

});

这是服务器的响应

['task 1 completed']

\n
\n
\n

['task 3 completed']


\n
\n
\n

['task 4 completed']


...

请求标题

Accept  text/plain, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language de,en-US;q=0.7,en;q=0.3
Authorization   Basic 12123456020600662232112311==
Host    123.123.123.123:1234
Origin  http://123.123.123.132
Referer http://123.123.123.123/index.php/db/SSRelaunch
User-Agent  Mozilla/5.0 (Windows NT 6.1; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0

响应标题

Access-Control-Allow-Head...    X-Requested-With, Content-Type, Authorization
Access-Control-Allow-Meth...    GET,POST,PUT,OPTIONS
Access-Control-Allow-Orig...    *
Content-Length  100000
Content-Type    text/plain
Date    Mon, 28 Jul 2014 18:06:27 GMT
Server  BaseHTTP/0.3 Python/2.7.3
javascript jquery ajax html5 xmlhttprequest
1个回答
0
投票

jQuery ajax API中没有内置进度函数,但您可以添加事件侦听器来处理信息。

查看有关如何执行此问题的答案:

What is the cleanest way to get the progress of JQuery ajax request?

© www.soinside.com 2019 - 2024. All rights reserved.