for循环中的Ajax请求

This is my code:

for (var i = 0; i < 20; i++) {
$.ajax({
    type: "GET",
    async: false,
    url: "/MyController/MyMethod",
    success: function (data) {
        if (i == 0) {
            $('#result_progress').hide();
            $('#result_msg').hide();
            $('#details').show();
        } else if (i == 1) {
            $.ajax({
            type: "GET",
            async: true,
            url: "/Import/Finish",
            success: function (data) {
                    ....                        
            });                                            
        }
        if (i < 2) {
            $('#details').html($('#details').html() + 'someText'));
        }                                        
    }
});

}

I don't want to use async: false because my browser stops working. How would I fix this in another way?

Your problem is that i has the value of end of loop when the callbacks are executed.

The standard solution to fix that is to add an intermediate immediately called function to protect the value of i :

for (var i = 0; i < 20; i++) {
   (function(i){
      ... your code
   })(i);
}

The call to the function creates a scope in which i is a different variable.

I think you should do it with some closure:

function makeReq(n){
   return function(){
      $.ajax({
        type: "GET",
        async: true,
        url: "/MyController/MyMethod",
        success: function (data) {
           if (n == 0) {
              $('#result_progress').hide();
              $('#result_msg').hide();
              $('#details').show();
           } else if (n == 1) {
              $.ajax({
                type: "GET",
                async: true,
                url: "/Import/Finish",
                success: function (data) {
                    ....                        
                });                                            
           }
           if (n < 2) {
               $('#details').html($('#details').html() + 'someText'));
           }                                        
       }
     });
   }
}

for (var i = 0; i < 20; i++) {
    makeReq(i);
}

This problem can be solved by creating a function and calling it on each iteration of the loop, while passing i; calling the function will form a brand new execution context where the value of i is retained and can be used in any way within that context.

Here's how I fixed it:

function run(i, howManyToRun, start) {
    if(i >= howManyToRun) return;

    $.ajax({
        type: "GET",
        async: false,
        url: "/MyController/MyMethod",
        success: function (data) {        
            ....
            run(++i, howManyToRun, start);
            ....                                    
        }
    });
}