我有以下情况。我想从服务器加载文件A,而服务器又将尝试加载文件A1,A2,A3,... An,并且每个文件A [1-n]将依次加载其他文件,这可以继续;但结束了。 我想使用延迟对象来设置它(以避免使用async:false挂起浏览器),但加载和解析文件的递归会让我困惑于如何设置对象。此外,还有一个要求,即在继续使用级别(l-1)之前,最高递归深度级别(l)必须完成。 对于没有递归的情况,这段代码可以正常工作,但是递归的情况并没有发生。递归Ajax延迟对象
var loadFile = function (index, url, scope, callback) {
$.ajax ({url: url, type: 'GET', dataType: 'text'})
.done (function (responseText) {
// store response in array
scope.requests[index] = responseText;
})
.fail (function (xhr, status, error) {
scope.requests[index] = 'error';
})
.always (function (responseText) {
// loop through entire response array from the beginning
for (var j = 0; j < scope.requests.length; j++)
{
if (scope.requests[j] === 'unprocessed') return;
else if (scope.requests[j] === 'error')
scope.requests[j] = 'done';
else if (scope.requests[j] !== 'done')
{
parseFile (scope.requests[j], scope, callback);
scope.requests[j] = 'done';
}
}
// if all are done then reset the array and run the callback
delete scope.requests;
if (callback) callback();
});
}
var parseFile = function (responseText, scope, callback) {
var lines = responseText.split("\n");
for (var l = 0; l < lines.length; l++) {
var line = lines[l];
line = line.replace (/^\s+/, ''); // remove leading white space
if (line.charAt(0) === '1') // file reference
{
var attrs = line.split (/\s+/);
// the file will exist in any of the paths in pathList
for (var i = 0; i < scope.pathList.length; i++) {
scope.requests.push ('unprocessed');
loadFile (++index, scope.pathList[i] + attrs[14], scope, callback);
}
}
}
}
var index = 0;
var this.requests = [];
this.requests.push ('unprocessed');
loadFile (index, fileAi, this, callback);
你好,我明白了什么代码做什么,但第一级之后,它只是停止。我已将代码放在http://www.virtuality.gr/AGG/EaZD-WebGL/test_lego.html并在控制台上输出。我尝试添加一个小缓存,因为几个文件重复,但我现在已经评论。我想,为了组成整个下载文件(递归完成后),我需要另一个数组。 – gaitat
我不确定编辑做了什么。我得到了同样的结果。只是第一级被解析。 pathList变量包含可能存在文件的目录。不是所有的路径,只有一个。所以在通过pathList的for循环中,只有一个会成功。其余的将失败。 – gaitat
好的,我认为我在编辑中做了一些愚蠢的事情:)但它很接近。将在一分钟后再次编辑。 –