当ajax错误时中断循环

时间:2014-03-08 13:00:52

标签: javascript loops

我在循环中调用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;
                        }
                    });
                }   

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

3 个答案:

答案 0 :(得分:3)

我最好使用这样的东西:

(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

答案 1 :(得分:2)

    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;
           }
      });
 }   

答案 2 :(得分:0)

您应该考虑使用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循环

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