You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript的countdown循环内调用GET接口查询PHP后端处理状态

实现方案

你可以在countdown函数里通过Fetch API调用后端的GET状态查询端点,根据返回的结果动态判断跳转地址即可,以下是修改后的可运行代码以及相关说明:

前端代码修改

<h3>
  Hang on, we're fetching the data ... <span id="countdown">10</span> seconds
</h3>

<!-- JavaScript part -->
<script type="text/javascript">
    // 总等待秒数
    var seconds = 10;
    // 替换为你自己的PHP状态查询端点地址
    const STATUS_QUERY_API = '/your_php_endpoint/check_status.php';
    
    async function countdown() {
        seconds = seconds - 1;
        // 优先更新倒计时显示,避免接口请求阻塞UI
        document.getElementById("countdown").innerText = seconds;

        // 每秒查询一次处理状态,可根据需求调整调用频率
        try {
            const response = await fetch(STATUS_QUERY_API);
            const result = await response.json();
            // 如果后端返回数据处理完成,可直接提前跳转,无需等倒计时结束
            if (result.status === 'success') {
                window.location.href = result.target_url;
                return;
            }
        } catch (err) {
            // 接口调用异常的容错逻辑,可按需调整
            console.error('状态查询失败', err);
        }

        if (seconds < 0) {
            // 倒计时结束后做最终状态校验
            try {
                const finalRes = await fetch(STATUS_QUERY_API);
                const finalResult = await finalRes.json();
                window.location.href = finalResult.status === 'success' 
                    ? finalResult.target_url 
                    : finalResult.coming_soon_url;
            } catch (err) {
                // 接口异常时默认跳即将上线页
                window.location.href = '你的默认即将上线页面地址';
            }
        } else {
            window.setTimeout(countdown, 1000);
        }
    }
    
    // 启动倒计时
    countdown();
</script>

后端PHP接口约定

你的PHP查询端点需要返回JSON格式的响应,参考实现代码如下:

<?php
// 若前后端域名不同,按需配置跨域
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');

// 你的业务逻辑:查询数据处理进度
$process_done = check_data_process_status(); // 替换为你自己的状态判断方法

if ($process_done) {
    echo json_encode([
        'status' => 'success',
        'target_url' => '处理完成后的跳转地址'
    ]);
} else {
    echo json_encode([
        'status' => 'pending',
        'coming_soon_url' => '即将上线页面地址'
    ]);
}
exit;
?>

可选优化点

  • 若觉得每秒调用接口对服务器压力过大,可新增变量控制调用频率,比如每2-3秒查询一次状态
  • 可根据业务需求调整逻辑:如果不需要提前跳转,仅需倒计时结束后再判断状态,把状态查询逻辑全部移到seconds < 0的分支内即可
  • 接口异常的重试、降级逻辑可根据实际业务场景调整

内容的提问来源于stack exchange,提问作者K997

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 03:27:04