Javascript 更改 window.location 并运行异步 ajax get

标签 javascript jquery ajax asynchronous

我想使用 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/

相关文章:

javascript - 如何使用 javascript 从字母数字字符串值中拆分数值?

javascript - 在 Javascript 中区分数组和 "hashes"

ajax - node express 服务器不响应 ajax

Javascript:删除由 ajax 响应设置的 cookie

javascript - 如何将 javascript 变量的值替换为表单字段?

javascript - 数据不会加载到模板中

javascript - jquery 发现没有获取无效元素

带点符号的 jQuery 多重选择器?

javascript - 如何在服务、技能、组合等中添加滑动效果?

javascript - 如何清除并重新填充下拉选项