Php Guzzle的异步请求无法正常工作

时间:2019-06-11 16:00:30

标签: php guzzle

我创建下面的代码,以发出异步请求以从API获取数据。

<?php
require 'vendor/autoload.php';
$url = "https://pucminas.instructure.com/api/v1/";

$client = new GuzzleHttp\Client(['base_uri' => $url]);

$headers = [
    'Authorization' => "Bearer 11111~dsgffdhstggfjsdhf",
    'Accept'        => 'application/json',    
];

$course_id = "2242";
set_time_limit(300);

$promise = $client->getAsync( 'courses/'.$course_id.'/students/submissions?student_ids[]=all&grouped=true&post_to_sis=false&enrollment_state=active&include[]=user&include[]=assignment&include[]=total_scores&per_page=1000', ['connect_timeout' => 600, 'headers' => $headers]);

$promise
->then(function ($response) {
echo 'Got a response! ' . $response->getStatusCode();
});

?>
<h2>Reports</h2>

我想当我加载页面时,它将在页面中显示文本“ Reports”,并且从API获取内容后(至少需要60秒),它将显示消息“获得响应”,但是这样是行不通的。

首先,页面会从API加载内容,然后才同时显示文本“报告”和“收到消息”。

我希望在加载页面时立即显示文本“报告”,而仅在从API加载数据时才显示文本“获得响应”。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

您只能从PHP脚本发送单个响应,即您的浏览器请求一个页面,PHP服务器会构建该页面并将其发送回。由于HTTP是无状态的,因此PHP服务器无法将页面更新“推送”到浏览器。

要实现所需的功能,您需要编写一些JavaScript,这些JavaScript将调用PHP脚本以启动耗时的异步承诺。然后,该承诺会在承诺完成后将结果写入文件(或数据库)。

然后,您需要第二个javascript函数,该函数会不断检查第二个php脚本。第二个PHP脚本将检查文件的内容(或数据库条目等)并返回结果。

您最好看看Axios之类的东西,然后完全丢掉PHP

https://www.npmjs.com/package/axios

相关问题