javascript 循环通过表格行和执行jquery AJAX 是不工作的

wwwo4jvm  于 2023-03-11  发布在  Java
关注(0)|答案(1)|浏览(130)

我正在尝试执行此代码:

var table = document.getElementById("tab");
    for (var i = 0, row; row = table.rows[i]; i++) {
       //rows would be accessed using the "row" variable assigned in the for loop
       let idd = row.cells[1].textContent;
       
       if(idd != 'Id' && idd != '') {
           $.ajax({
                type: "POST",
                url: "/numordiniperiodoagenti",
                data: {id : idd, start: sstart, end: eend},
                success: function(response){
                    row.cells[10].textcontent = 'p'; //or response as it should be
                }
            });
        }
    }

但是在这个ajax调用中似乎无法访问row
我错过了什么?

2admgd59

2admgd591#

由于变量row的作用域仅在for循环内, AJAX 的回调函数是另一个作用域,因此您无法访问ajax回调函数内的变量row。要解决此问题,您可以在回调函数内定义其他变量,然后将row值赋给该新变量。

var table = document.getElementById("tab");
for (var i = 0, row; row = table.rows[i]; i++) {
   //rows would be accessed using the "row" variable assigned in the for loop
   let idd = row.cells[1].textContent;
   
   if(idd != 'Id' && idd != '') {
       $.ajax({
            type: "POST",
            url: "/numordiniperiodoagenti",
            data: {id : idd, start: sstart, end: eend},
            success: function(response){
                var target_row = row; 
                target_row.cells[10].textcontent = 'p'; //or response as it should be
            }
        });
    }
}

相关问题