Jas*_*ich 3 google-api google-apps-script google-classroom
目前,我有一个脚本可以正确列出 Google Classroom 中某个班级的学生,但它没有列出所有学生,只有前 30 名。我需要它列出所有学生,无论有多少有。我现在拥有的是以下内容:
function listStudents() {
var s = SpreadsheetApp.getActiveSpreadsheet();
var sh = s.getSheetByName('CLASS');
var r = sh.getDataRange();
var n = r.getNumRows();
var d = r.getValues();
for (x = 0; x < n; x++) {
var i = d[x][0];
if(i == ''){ continue; } else if (i == 'D') {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheetByName('LISTSTUDENTS');
var tea = Classroom.Courses.Students.list(d[x][8]);
var t = tea.students;
var arr = [];
try {
for (i = 0; i < t.length; i++) {
var c = t[i];
var ids = c.profile;
var em = ids.emailAddress;
arr.push([em]);
}
}
catch (e) { continue; }
sh.getRange(d[x][14], d[x][15], arr.length, arr[0].length).setValues(arr);
}
}
}
Run Code Online (Sandbox Code Playgroud)
您在查询中只收到 30 名学生,因为您只访问了结果的第一页。几乎每个“高级服务”都以类似的方式运行集合,因为它们在调用中返回可变数量的项目(通常达到可以在查询中指定的大小,但有限制)。这是为了确保每个使用它的人都能及时获得服务。
例如,考虑 Bob(来自会计)。这种请求分页风格意味着他不能请求一个包含 20,000 个项目的响应,在此期间,其他人的服务速度较慢。但是,他可以请求接下来的 100 个项目 200 次。虽然 Bob 正在使用他最近查询中的这 100 个项目,但其他人可以在不中断的情况下使用该服务。
要进行设置,您需要使用保证至少执行一次的代码循环,并使用nextPageToken包含在对调用的响应中的.list()来控制循环。在 Javascript / Google Apps Script 中,这可以是一个do .. while循环:
// Runs once, then again until nextPageToken is missing in the response.
const roster = [],
// The optional arguments pageToken and pageSize can be independently omitted or included.
// In general, 'pageToken' is essentially required for large collections.
options = {pageSize: /* reasonable number */};
do {
// Get the next page of students for this course.
var search = Classroom.Courses.Students.list(courseId, options);
// Add this page's students to the local collection of students.
// (Could do something else with them now, too.)
if (search.students)
Array.prototype.push.apply(roster, search.students);
// Update the page for the request
options.pageToken = search.nextPageToken;
} while (options.pageToken);
Logger.log("There are %s students in class # %s", roster.length, courseId);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1594 次 |
| 最近记录: |