Rest API筛选超5000条列表项异常问题求助(附代码)
问题原因
SharePoint列表默认设置了5000条视图阈值,直接用$top=5000只能获取前5000条数据,无法拿到超过阈值的所有结果。另外你代码里用了同步请求(async: false),这种方式不适合处理分页的异步数据获取场景。
修复后的代码
1. 改造异步分页获取函数
function GetAllListItems(listName, restParams, onSuccess) { var allItems = []; var baseUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('" + listName + "')/items"; var requestUrl = baseUrl + (restParams ? "?" + restParams : ""); function fetchPage(url) { jQuery.ajax({ url: url, type: "GET", headers: { "accept": "application/json; odata=verbose" }, async: true, success: function (data) { // 合并当前页数据到总集合 allItems = allItems.concat(data.d.results); // 检查是否存在下一页数据 if (data.d.__next) { fetchPage(data.d.__next); } else { // 所有数据获取完成,执行回调 onSuccess(allItems); } }, error: function (xhr, status, error) { alert("获取列表项失败:\n" + xhr.responseText); } }); } // 启动第一页数据请求 fetchPage(requestUrl); }
2. 调用改造后的函数
// 构建REST查询参数 var restParams = "$select=Category,QueryBalanceb_x002f_f,NormalBalanceb_x002f_f,Received,Processed,Queried,Query_x0020_Resolved,Query_x0020_Balance_x0020_c_x002,Normal_x0020_Balance_x0020_c_x00,Client_x0020_Name/Title,Client_x0020_Name/Id,CSM/Id,CSM/Title,CPT/Id,CPT/Title" + "&$filter=(Created ge datetime'" + StartDate + "T20:00:00.000Z' and Created le datetime'" + EndDate + "T20:00:00.000Z')" + (ClientID == '' ? '' : " and Client_x0020_Name/Id eq " + ClientID) + "&$expand=Client_x0020_Name,CSM,CPT" + "&$top=5000"; // 每页取满阈值上限的5000条数据 // 调用函数获取所有数据 GetAllListItems("Daily Inputs", restParams, function(allItems) { BindDashboard(allItems, TbaleID, staffId, Btype); });
关键改动说明
- 移除了同步请求(
async: false),改用异步递归分页,避免阻塞浏览器运行 - 通过返回结果中的
__next属性判断是否存在下一页,循环拉取所有数据 - 将所有分页数据合并后再传入回调函数,保证
BindDashboard能拿到完整的数据集
内容的提问来源于stack exchange,提问作者Yogesh kumar
相关产品推荐
相关产品推荐

