我想在Teamwork API中显示所有数据任务,但是Teamwork每页只显示250个数据任务。我曾尝试使用while语句,但这会导致无限循环。
我期待输出,如果所有任务都已发出,因此params页面不会再次递增
$(function() {
let tasks;
while (tasks) {
url = '/data.json?page=' + page++
$.ajax(url, {
type: 'GET',
success: function(data) {
$.each(data['todo-items'], function(key, task) {
tasks = data['todo-items'].length
})
}
})
}
})发布于 2021-05-20 23:21:33
检查HTTP标头。项目总数在X-Records HTTP标头中。
有3个不同的标头与项目API的分页相关。如果您转到浏览器中的开发人员工具,并执行一个“GET”调用。如果您检查浏览器,您将在headers部分看到。有3个头部值:
X-Page -当前返回的页面X-Pages -可用页面总数X-Records -可用项目总数
您可以通过调用相同的接口调用并添加参数&page=n来请求特定页面,其中n是您想要的页面。例如:第2页的&page=2,第5页的&page=5。
下面是我们用来循环结果的PHP函数
/**
* NOTE: Can only pull 500 at a time. see docs, after that must pull pages
* By default, pulls all active projects, ordered by project name, includes custom fields.
*
* @link https://developer.teamwork.com/projects/api-v2/ref/custom-fields/getprojectsapiv2projectsjson
* @example https://deltasystemsgroup.teamwork.com/projects/api/v2/projects.json?includeCustomFields=true
* @param none
* @return array of entire response. you'll want to pull off $responseData['projects'] and $responseData['customFields']
* @throws Exception
*/
public function getAllProjectsRaw()
{
// DO NOT USE V1 - no custom fields - https://developer.teamwork.com/projects/api-v1/ref/projects/get-projects-json
$page = 0;
$pageSize = 500;
$all_projects = [];
$all_custom_fields = []; //for each project
do {
$page++;
$response = $this->makeApiRequest("/projects/api/v2/projects.json",
[
'query' => [
'includeCustomFields' => 'true',
'page' => "{$page}",
'pageSize' => "{$pageSize}"
],
]
);
$responseData = json_decode(
$response->getBody(), true);
if (!$responseData) {
throw new Exception('Page ' . $page . ' : Failed to decode Teamwork time entry API response as JSON');
}
if (!isset($responseData['STATUS'])) {
throw new Exception('Page ' . $page . ' : Teamwork time entry API response did not include STATUS');
}
if ('OK' !== $responseData['STATUS']) {
throw new Exception('Page ' . $page . ' : Teamwork time entry API response did not respond with
STATUS = OK. Status response was: ' . $responseData['STATUS']);
}
if (1== $page) {
$all_custom_fields = array_merge($all_custom_fields, $responseData['customFields']);
}
$all_projects = array_merge($all_projects, $responseData['projects']);
//The total number of projects is in the X-Records HTTP header.
// X-Pages will be set to the total number of pages, and X-Page will be set to the current page.
//so we added a loop
$xPages = -1;
if ($response->getHeader('X-Pages')[0]) {
$xPages = (int)$response->getHeader('X-Pages')[0];
}
} while ($page < $xPages);
$custom_fields_and_all_projects['customFields'] = $all_custom_fields;
$custom_fields_and_all_projects['projects'] = $all_projects;
return $custom_fields_and_all_projects;
}https://stackoverflow.com/questions/57489502
复制相似问题