如何在url中发送带有循环id号参数的ajax调用



我想在url starts request.php中发送带有循环参数[id]的ajax调用?id=1结束id=9并在3秒钟后发送每个呼叫。我是JavaScript的初学者,我不知道从哪里开始这个想法,这是我的代码:

$.ajax({
type: 'POST',
url: 'request.php?id=1',
data: {apiId:actionBtn},
dataType: 'json',
cache: false,
beforeSend: function(){
$('.submitBtn').attr("disabled","disabled");
$('#addApi').css("opacity",".5");
},
success: function(response){
}
});

首先,将id转换为变量let id = 1;。然后您可以使用JavaScriptsetInterval(https://developer.mozilla.org/en-US/docs/Web/API/setInterval)函数,每x秒调用一次函数。

let id = 1;
// you can use a "fat-arrow" function or a function reference, look at the docs
const interval = setInterval(() => {
// your code here...
// use the variable "id" and increment it
i++;
// stop the interval when id is greater 9
if (id > 9) {
clearInterval(interval);
}
}, 3000); // 3000 is the time in milliseconds
// create a loop
for (let i = 0; i <= 9; i += 1) {
// create a timeout
setTimeout(() => {
$.ajax({
type: 'POST',
// set the id
url: `request.php?id=${i}`,
data: {apiId:actionBtn},
dataType: 'json',
cache: false,
beforeSend: function(){
$('.submitBtn').attr("disabled","disabled");
$('#addApi').css("opacity",".5");
},
success: function(response){
}
});
}, i * 3000)
}

最新更新