在下面的代码中,我运行了一个 for 循环,它设置了一个变量“nets”,该变量针对数组 netnos[]
中的每个项目进行更新。 .
然后我调用 Ajax 来处理 php 以生成列表,该列表正确输出到 response
。
我正在设置一个变量theList
在 success 函数内部,它结合了 nets
随响应变化。然后附加到我的子网 div。
问题是这里的“nets”变量永远不会从其原始值更新,即使响应是正确的。这意味着data: {q : nets}
确实改变正确。
那么为什么是 nets
成功中:没有被更新?它始终保留数组中第一项的值。
<script>
$(document).ready(function(){
$(document).on('click', '.subnetkey', function() {
var thelist = "";
var strr = $(".subnetkey").val(); // The string of net numbers like 789, 790
var count = strr.split(',').length; // How many are in the string 2 in the test case
var netnos = strr.split(","); // The string made into an array of nets
$("#subNets").removeClass("hidden"); // Remove the hidden from the subNets div
for (i=0; i<count; i++) { // Loop through
var nets = netnos[i]; // Find each net number from the array
// alert('i= '+i+' nets= '+nets); // When i=0 nets = 789, when i=1 nets = 790
$.ajax({
type: "GET",
url: "getactivities.php",
data: {q : nets},
success: function(response) {
var thelist = "#"+nets+"<br>"+response+"<br><br>";
$("#subNets").append(thelist);
},
error: function() {
alert('Sorry no nets.');
}
}) // End of ajax
} // End for loop
}); // End of on(click) function
}); // End of ready function
</script>
最佳答案
问题是名称 nets
在 for 循环中按词法绑定(bind),并且它的值会在迭代 i
时发生变化。解决此问题的一个简单方法是使用 Array.forEach,因为每次调用用于迭代的函数都会有自己的 nets 绑定(bind) - 这会导致代码也更短,因为您甚至不需要 i
!
$(document).ready(function() {
$(document).on("click", ".subnetkey", function() {
var strr = $(".subnetkey").val();
var netnos = strr.split(",");
$("#subNets").removeClass("hidden");
netnos.forEach(nets => {
$.ajax({
type: "GET",
url: "getactivities.php",
data: { q: nets },
success: function(response) {
var thelist = "#" + nets + "<br>" + response + "<br><br>";
$("#subNets").append(thelist);
},
error: function() {
alert("Sorry no nets.");
},
});
});
});
});
关于javascript - 变量成功 : of Ajax which is running in a loop not being updated,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51884358/