我正在运行一个循环函数,其中包含 AJAX 请求,AJAX 上的成功函数需要访问循环函数外部的计数器变量,但它不会访问它。
var updateCount = 10;
var runCount = 0;
$('#main-table .changed').not("[value='0']").closest('tr').each(function(e){
if($(this).closest('tr').find('.changed').val() == 1){
var row = $(this).closest('tr');
var notes = row.find('input[name="notes"]').val();
var category = row.find('select[name="category"]').val();
var fileId = row.find('select[name="file"]').val();
var fileRow = row.find('.file-id').val();
var quarter_id = row.find('.quarter-id').val();
$.ajax({
url: '/myurl',
type: "POST",
data: {_token: CSRF_TOKEN, 'file_row' : fileRow, 'files' : fileId, 'notes': notes, 'category' : category, 'type' : type, 'quarter': quarter_id, 'row_count':updateCount},
success: function(data){
if(data == 0){
console.log("yes");
//I need to increment the runcount here, but it wont increment
runCount++;
}
}
});
//If i increment the run count here outside the AJAX request, it works
runCount++;
if(runCount == updateCount){
console.log("Done");
}
};
});
如注释中所述,我需要访问 ajax success 函数内的 runCount
变量,但我不能。如果我在 AJAX 请求之外访问它,它就可以正常工作。
只是为了确认,ajax 请求正在工作,因为它每次都在控制台记录 yes
,所以我不明白为什么它不会增加?
最佳答案
可能有更好的方法来做到这一点,但一个可靠的方法是创建另一个函数(在 JavaScript 中)并用它更新它,例如:
function bumpRunCount(){
runCount++;
}
然后从 ajax 结果调用该函数。这当然取决于 runCount
的范围。我只是提到这一点,因为你提到了一个功能,而我没有看到它,所以你可能只显示了该功能的一部分。如果是这种情况,您需要确保 var runCount 是全局命名空间的一部分;或者至少可以访问。
关于javascript - 无法从ajax请求内部访问作用域变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48279609/