2016-12-14 110 views
0

我正在使用jQuery的GET方法在循环中读取文本文件。通过返回的信息,我为select元素添加了一些选项。我的问题是有时候这些选项会混乱。我的代码如下:jQuery:使用get方法在循环中读取多个文件

for (var i = 1; i <= n; i++) 
{ 
    $.get("./file" + i + ".txt", function(data) { 
     $("select").append("<option>" + data + "</option>"); 
    }); 
} 

我试图找到一种解决方案,不涉及合并所有数据在1个文件中。谢谢您的帮助!

+0

因为异步调用会在不同的时间回来。与您的设计有关的问题是,进行所有这些呼叫是非常低效的。 – epascarello

回答

0

我的问题是,有时这些选项会加入混乱。我的代码如下:

问题:这是由于async电话。你当前的代码只是发送请求到一个文件,然后跳转到下一个迭代,它会发送请求并跳转到下一个等等。你真的无法控制响应什么时候回复,也没有控制权来控制它。

解决方案:既然你正在处理async过程的更好,如果你使用递归函数在for循环。看下面的代码来理解我的意思。

function GetFile(fileNumber) { 
 
    $.get("./file" + fileNumber + ".txt", function(data) { 
 
    $("select").append("<option>" + data + "</option>"); 
 
    fileNumber++; // since the files was read successfully lets increment the number to next file 
 
    if(fileNumber <= n){ // if we have not reached the limit 
 
     GetFile(fileNumber); // get the next file 
 
    } 
 
    }); 
 
} 
 

 
GetFile(1); //initiate the recursive function by passing the first number

由于您没有提供什么n是我刚才用它作为是在我的代码也一样,考虑的变量可在该范围的详细信息。

解释了解决方案:创建一个函数,接受一个数字作为输入并执行该文件一个get请求名为"file" + fileNumber + ".txt"success回调get功能,我会增加数量,并检查其小于或等于极限n如果它小于或等于那么我继续并通过传递新的号码来调用相同的功能。这将持续到我们达到极限。

注意:如果任何请求发生错误,上述逻辑将停止。如果您想要继续,即使响应中有错误,您也可以添加.fail()处理程序..请参见下文。

$.get("./file" + fileNumber + ".txt", function(data) { 
    //above shown logic 
    }).fail(function() { 
    console.log("There was an error while fetching file"+fileNumber +".txt"); 
    fileNumber++; 
    if(fileNumber <= n){ // see if next file exist 
     console.log("Processing next file!!"); 
     GetFile(fileNumber); // get the next file 
    } 
    }); 
相关问题