项目总数
如果您要查找列表本身中的项目总数(而不是过滤视图中的项目数),您可以直接访问列表的 $count 属性。
"/_vti_bin/ListData.svc/MPIC/$count"
这将返回项目计数。
分页(如有必要)
要使用 REST 模拟分页,您可以执行以下操作:
- 使用
$skip=n 参数根据$orderby 参数跳过第一个n 条目
- 使用
$top=n 参数根据$orderby 和$skip 参数返回顶部的n 条目。
处理异步回调
您的代码中最大的问题是您有两个异步函数回调,用于获取结果项的总和。由于这些函数调用不在同一范围内执行,因此您不能同时访问它们的值。
一种解决方法是使用函数链接将您的逻辑向前移动到回调函数中。
使用 $skip 和 $top 的示例
这是一个使用$skip 和$top 参数和您提供的代码的示例,在更新ALLCount1 元素的文本之前使用递归回调函数获取结果总数。
$.getJSON("/_vti_bin/ListData.svc/MPIC?$select=Id&$orderby=Id&$top=1000&$inlinecount=allpages", function (data) {
var count = data.d.results.length;
updateTotal(count);
});
function updateTotal(total){
$.getJSON("/_vti_bin/ListData.svc/MPIC?$select=Id&$orderby=Id&$skip="+total+"&$top=1000&$inlinecount=allpages", function (data) {
var count = data.d.results.length;
if(count > 0){
updateTotal(total+count);
}
else{
$("#ALLCount1").text(total);
}
});
}
使用 $skiptoken 和 $top 的示例
如果您受限于使用$skiptoken 而不是$skip(例如在查询包含 5000 多个项目的列表时),您肯定仍然可以使用它,但您还有更多工作要做。
$skip 只想要跳过的项目数,$skiptoken 想要跳过最后一个项目的 ID。
代码与上面的代码基本相同,但您需要深入研究数据结果并提取最后一项的 ID 值。我将把它作为练习留给读者。
updateTotal(0,0);
function updateTotal(skip,total){
$.getJSON("/_vti_bin/ListData.svc/MPIC?$select=Id&$orderby=Id&$skiptoken="+skip+"&$top=1000&$inlinecount=allpages", function (data) {
var count = data.d.results.length;
if(count > 0){
var lastItemId;
// TODO: get last item id from results here
updateTotal(lastItemId,total+count);
}
else{
$("#ALLCount1").text(total);
}
});
}