首页 > 解决方案 > 运行长 php 脚本的最佳实践

问题描述

我试图弄清楚如何在不让用户永远等待的情况下运行长 php 脚本。我有一个脚本需要运行几个函数,每个函数都需要几秒钟才能运行。

我想知道有没有一种方法可以让我的 php 脚本在完成运行之前将其数据返回给调用者?

 <?php
  echo http_response_code(200);
  sleep(60);
  run_other_code();
 ?>

一个非常简单的示例,但我正在寻找脚本来回显响应,然后在后台运行其余代码。这样的事情可能吗?

标签: php

解决方案


使用 ajax 调用来执行此类任务,请看下面的示例

$.ajax({
    url: "getData.php",
    error: function(){
        // this code will fire when timeout is reached
    },
    success: function(){
        //this code will fire when the script is finished doing the task
    },
    timeout: 61000 // always kepp it more than the time total time taken by your script
});

希望能帮助到你


推荐阅读