首页 > 解决方案 > 为 AJAX 请求并行获取 Apache PHP 响应

问题描述

我的 AJAX 请求大约需要 7 秒才能完成。对于一个页面,我有很多这样的请求。服务器对每个请求几乎按顺序响应。对于 10 个请求,我在 1 分钟后得到最后一个请求的响应。有没有办法独立获得回复?我尝试了简单的 $http.get 以及 jQuery AJAX 来进行调用。我想在 7 秒的处理时间后几乎立即获得所有请求的响应。
例如,我的 $http.get 代码如下:

$q.all([
            $http.get('http://localhost/ajaxtest/index.php?route=test/sleepTest&seq=' + 0),
            $http.get('http://localhost/ajaxtest/index.php?route=test/sleepTest&seq=' + 1),
            $http.get('http://localhost/ajaxtest/index.php?route=test/sleepTest&seq=' + 2),
            $http.get('http://localhost/ajaxtest/index.php?route=test/sleepTest&seq=' + 3),
            $http.get('http://localhost/ajaxtest/index.php?route=test/sleepTest&seq=' + 4),
            $http.get('http://localhost/ajaxtest/index.php?route=test/sleepTest&seq=' + 5),
            $http.get('http://localhost/ajaxtest/index.php?route=test/sleepTest&seq=' + 6),
            $http.get('http://localhost/ajaxtest/index.php?route=test/sleepTest&seq=' + 7),
            $http.get('http://localhost/ajaxtest/index.php?route=test/sleepTest&seq=' + 8),
            $http.get('http://localhost/ajaxtest/index.php?route=test/sleepTest&seq=' + 9)
        ])
            .then(function(responses) {
                console.log( responses[0].data);
                console.log( responses[1].data);
                console.log( responses[2].data);
            });

在服务器端,我正在运行 sleep() 函数以进行测试。代码如下:

public function sleepTest(){
    session_write_close();
    sleep(10);
    print $this->request->get["seq"];
}

XHTTP 请求结果一个接一个地出现(大约在前一个响应出现后 10 秒)。请查看屏幕截图中的响应时间,服务器在前一个响应的 10 秒后响应每个请求。最后一个响应在 100 秒后出现,而我希望所有响应都在 10 秒后出现。

更新:一些导师提到了另一个问题,该问题的答案已被接受,但该答案尚不清楚。我遵循了参考文件,但无法得到我所期望的。添加 session_write_close(); 部分帮助我,它同时做出 6 个响应,这意味着我一次从服务器 6 获得 AJAX 响应。我还能做些什么来同时获得所有(10+)个响应吗?

随时间变化的请求和响应的屏幕截图

更新截图: 随着时间的推移更新了请求和响应的屏幕截图

标签: phpjqueryangularjsajaxapache

解决方案


推荐阅读