在我的插件中,我想在WordPress中异步调用10个或更多HTTP请求,这样我就不需要等待任何人的响应。Wordpress中是否有任何方式支持此功能并与不同的Wordpress版本兼容?
如何在WordPress中运行多个异步HTTP请求?
1 个回复
SO网友:alpipego
(内置)Requests
类允许您同时调用多个请求:Requests::request_multiple
.
<?php
$requests = Requests::request_multiple([
[
\'url\' => \'https://www.mocky.io/v2/5acb821f2f00005300411631\',
\'type\' => \'GET\',
\'headers\' => [
\'Accept\' => \'application/json\'
],
],
[
\'url\' => \'https://www.mocky.io/v2/5acb821f2f00005300411631\',
\'type\' => \'POST\',
\'headers\' => [
\'Accept\' => \'application/json\'
],
\'data\' => json_encode([
\'text\' => \'My POST Data\'
])
],
[
\'url\' => \'https://www.mocky.io/v2/5acb82ee2f00005100411635\',
\'type\' => \'POST\',
\'headers\' => [
\'Accept\' => \'application/json\'
],
\'data\' => json_encode([
\'text\' => \'More POST Data\'
])
],
]);
foreach ($request as $request) {
if ($request->status_code !== 200) {
// handle error
}
// handle success
echo $request->body;
}
结束