我收到错误
Uncaught SyntaxError:非法中断语句
在break;
上,如果服务器返回5,我想停止for
循环。我使用下面的代码:
<script type="text/javascript">
function getrblstatus(rbl, hash) {
var rblhosts = [<?php echo $rblhosts ?>];
var ActiveRbls = rblhosts.length;
var progress = '1';
for (i = 0; i < ActiveRbls; i++) {
///// Post data to server /////
$.ajax({
url: '<?php echo $site_url?>/includes/lib/ajax.php',
data: {
action: 'getrblstatus',
for: rbl,
hash: hash,
rbl_host: rblhosts[i]
},
type: 'post',
success: function (data) {
var percent = (progress/ActiveRbls)*100;
percent = percent.toFixed(2);
if(data == 5) {
console.log('Hash not correct');
break;
}
else{
$('#rbl_table > tbody').append(data);
$('#progressbar').width(percent+'%');
$("#progressbar").html(percent+"% Completed");
progress ++;
continue;
}
}
});
}
}
</script>
答案 0 :(得分:1)
您不能将异步代码(AJAX调用)与同步代码混合(用于/ break / continue)。所以你可以await
AJAX请求:
async function getrblstatus(rbl, hash) {
var hosts = [<?php echo $rblhosts ?>], progress = 1;
for (const rbl_host of hosts) {
const data = await new Promise((success, error) => $.ajax({
url: '<?php echo $site_url?>/includes/lib/ajax.php',
data: {
action: 'getrblstatus',
for: rbl,
hash: hash,
rbl_host
},
type: 'post', success
}));
var percent = (progress++ / hosts.length) * 100;
if(data == 5) {
console.log('Hash not correct');
break;
}
else {
$('#rbl_table > tbody').append(data);
$('#progressbar').width(percent+'%');
$("#progressbar").html(percent+"% Completed");
}
}
}
由于await
,break;
位于for
循环级别。