AJAX错误时断开循环



i ajax在循环中调用,当不存在文件时,我需要打破循环。看起来这样:

                for(m=1; m<10; m++){    
                    $.ajax({
                        type: "GET",
                        url: "/config/" + m + ".xml",
                        async : false,
                        dataType: "xml",
                        success: function(xml) {
                            alert("File Exist");                                                            
                        },
                        error: function(xml) {
                            alert("File not exist");
                            break;
                        }
                    });
                }   

当我从错误函数中删除断路时,它将警报"不存在文件",但是当我离开该破坏时,它会完全断开整个脚本。我只需要在不存在文件时才打破循环。

我最好使用这样的东西:

(function loadConfig(n) {
    $.ajax({
        type: "GET",
        url: "/config/" + m + ".xml",
        dataType: "xml",
        success: function (xml) {
            alert("File Exist");
            if (n < 9) loadConfig(n + 1);
        },
        error: function (xml) {
            alert("File not exist");
        }
    });
})(0);

这将提出通常对UX更好的非阻滞请求。

demo

    var m=1;
    while(m<10){    
       $.ajax({
           type: "GET",
           url: "/config/" + m + ".xml",
           async : false,
           dataType: "xml",
           success: function(xml) {
               alert("File Exist");   
               m++;                         
           },
           error: function(xml) {
               alert("File not exist");
               m=10;
           }
      });
 }   

您宁愿考虑使用while循环添加其他条件(即使您也可以在for循环条件下执行此条件

var m = 1, fileExists = true;
while ( m<10 && fileExists ){
   $.ajax({
       type: "GET",
       url: "/config/" + m + ".xml",
       async : false,
       dataType: "xml",
       success: function(xml) {
           alert("File Exist");                                                            
       },
       error: function(xml) {
           alert("File not exist");
           fileExists = false;
       }
   });
   m++;
}

或for for loop

var fileExists = true;
for(m=1; m<10 && fileExists; m++){
    // ...
}

最新更新