jQuery ajax loop and iteration scope

前端 未结 4 731
终归单人心
终归单人心 2021-01-25 23:07

I\'m wondering why in the code below the i variable still shows \"5\" instead of showing \"1\" then \"2\" the

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-25 23:48

    This is due to Closures in JavaScript. Here's the fix -

    for (var i = 0; i < 5; i++) { 
       (function(i){
        $.ajax({
            url: '/echo/html/',
            method:'post',
            data: {
                html: 'Ajax data'
            },
            success: function (resp) {
                $('#success').append(i) 
            }
        })
        })(i);
    
        $('#outsideAjax').append(i); 
    }
    

提交回复
热议问题