开发者

jquery :eq() selector don't work with variable (proper syntax) in ajax success function

开发者 https://www.devze.com 2023-04-04 05:01 出处:网络
I am trying to fill 3 divs using this code for(va开发者_JS百科r i = 0; i<3; i++){ $.ajax({ type: \"post\",

I am trying to fill 3 divs using this code

                        for(va开发者_JS百科r i = 0; i<3; i++){ 
                        $.ajax({
                                        type: "post",
                                        url: "/cake/orders/calendar/", 
                                        data: postData[i],
                                        success: function(response) { $(".ajaxCell:eq("+ i +")").html(response);},

                        });
                        }

Seems like everything is allright, variables are set, response recieved... and works with :eq(0) ...or 1 or 2 But I can't get it working with variable.

Am I missing something?


You're capturing the variable not the value of the variable in each iteration of the loop. When the request returns it uses the value of the variable at the time the request returns, not when the request was made. Call a function which does the ajax request with the index as an argument so that the value is captured in that function invocation.

for(var i = 0; i<3; i++){
   doRequest(i);
}

function doRequest(i) {
    var selector = ".ajaxCell:eq("+ i +")";
    $.ajax({
             type: "post",
             url: "/cake/orders/calendar/", 
             data: postData[i],
             success: function(response) { $(selector).html(response);},
    });
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号