duangan6797 2016-11-01 08:57
浏览 101
已采纳

如果当前页面加载x秒,则重定向到另一个页面?

Just curious if this could be possible. I am using an API and a function can sometimes take quite awhile to complete or even times out depending how it feels. Is there a way (Either with PHP, Javascript etc.) to be able to stop the page from loading after X amount of seconds and re-direct to another page?

Specifically, I'm using a form which is posted to the API using the standard form post mechanism.

  • 写回答

1条回答 默认 最新

  • douyang2530 2016-11-01 09:33
    关注

    Depending on what it is that delays the slow page's response, the browser may not tear down the previous page for some time after the form submission. That means you have the opportunity to use a setTimeout to do the redirect.

    document.querySelector("selector-for-the-form").addEventListener("submit", function() {
        setTimeout(function() {
            location.href = "/path/to/redirect/to";
        }, 3000); // 3000 = three seconds
    }, false);
    

    That works for me on Chrome, Firefox, and IE when posting to this simple PHP page in my default setup, which does a five-second busy-wait:

    <!doctype html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Delayed</title>
    <style>
    body {
        font-family: sans-serif;
    }
    </style>
    </head>
    <body>
    <?php
    $end = time() + 5;
    while (time() < $end) {
        // wait
    }
    ?>
    <p>Done: <?php echo $_POST["foo"]?></p>
    </body>
    </html>
    

    Again, though, it depends on whether it takes several seconds for the API page to start sending data to the browser. If it's not caching, for instance, and starts sending a response right away but then takes a long time to finish sending its response, the browser may tear down the page and start building the new one.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用