我想使用 GET 请求启动 ajax 循环来检查 Controller 的状态。一旦循环开始,我想通过更改 window.location 来开始文件下载。
但是我从这段代码中没有得到console.logs,为什么?
function getExcelIKT() {
setInterval(function () {
$.ajax({
type: 'GET',
url: getDownloadCSVForIKTStatusUrl,
dataType: 'json',
async: 'true',
success: function (DownloadCSVForIKTStatus) {
console.log(DownloadCSVForIKTStatus);
}
});
}, 3000);
window.location = downloadExcelUrlIKT;
}
最佳答案
function getExcelIKT() {
setInterval(function () {
$.ajax({
type: 'GET',
url: getDownloadCSVForIKTStatusUrl,
dataType: 'json',
async: 'true',
success: function (DownloadCSVForIKTStatus) {
console.log(DownloadCSVForIKTStatus);
if (false) { //change to some conditions
window.location = downloadExcelUrlIKT;
}
}
});
}, 3000);
}
只需将 if (false) {
更改为 if (DownloadCSVForIKTStatus.success) {
为什么看不到console.logs?因为 setInterval
和 $.ajax
函数是异步的。例如
setTimeout(function () {
console.log(1);
setTimeout(function () {
console.log(2);
},0);
console.log(3);
},0);
console.log(4);
结果将为4 1 3 2
。 (我使用 setTimeout
而不是 setInterval
,即使超时为 0 秒,它也是异步的)
关于Javascript 更改 window.location 并运行异步 ajax get,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27941722/