通過 CAML Query 獲取列表項
基本例子
使用 SP.CamlQuery 物件的 set_viewXml
方法指定用於檢索專案的 CAML 查詢。
SP.SOD.executeOrDelayUntilScriptLoaded(showListItems,"core.js");
function showListItems(){
var clientContext = new SP.ClientContext();
var list = clientContext.get_web().get_lists().getByTitle("List Title");
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml(
"<View><Query>" +
"<Where>" +
"<Eq><FieldRef Name=\"Title\"/><Value Type=\"Text\">Value</Value></Eq>" +
"</Where>" +
"<OrderBy><FieldRef Name=\"Modified\" Ascending=\"FALSE\"/></OrderBy>" +
"</Query>"+
//"<RowLimit>5000</RowLimit>" +
"</View>");
var items = list.getItems(camlQuery);
clientContext.load(items);
clientContext.executeQueryAsync(function(){
var itemArray = [];
var itemEnumerator = items.getEnumerator();
while(itemEnumerator.moveNext()){
var item = itemEnumerator.get_current();
var id = item.get_item("ID");
var title = item.get_item("Title");
itemArray.push(id + ": " + title);
}
alert("ID: Title\n"+itemArray.join("\n"));
},function(sender,args){alert(args.get_message());});
}
分頁 CAML 查詢的結果
你可以利用 CAML 查詢中的 RowLimit
元素,僅檢索每個查詢的結果子集。
使用列表項集合的 get_listItemCollectionPosition
方法檢索當前位置,然後使用該值作為 SP.CamlQuery 物件的 set_listItemCollectionPosition
方法中的引數來檢索下一批結果。
SP.SOD.executeOrDelayUntilScriptLoaded(showListItems,"sp.js");
function showListItems(){
var itemArray = [];
var clientContext = new SP.ClientContext();
var list = clientContext.get_web().get_lists().getByTitle("List Title");
var viewXml =
"<View><Query>" +
"<OrderBy><FieldRef Name=\"Modified\" Ascending=\"FALSE\"/></OrderBy>" +
"</Query>"+
"<RowLimit>1</RowLimit>" +
"</View>";
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml(viewXml);
var items = list.getItems(camlQuery);
clientContext.load(items);
clientContext.executeQueryAsync(loadResults,showError);
function loadResults(){
var resultsFound = false;
var itemEnumerator = items.getEnumerator();
while(itemEnumerator.moveNext()){
var item = itemEnumerator.get_current();
var id = item.get_item("ID");
var title = item.get_item("Title");
itemArray.push(id + ": " + title);
}
var pos = items.get_listItemCollectionPosition();// <- get position
if(pos !== null){ // <-- position is null when no more results are returned
if(confirm("Results so far: \nID: Title\n"+itemArray.join("\n"))){
camlQuery = new SP.CamlQuery();
camlQuery.set_listItemCollectionPosition(pos);// <- set position for next batch
camlQuery.set_viewXml(viewXml);
items = list.getItems(camlQuery);
clientContext.load(items);
clientContext.executeQueryAsync(loadResults,showError);
}
}else{
alert("Total Results: \nID: Title\n"+itemArray.join("\n")); // <- display when no more results
}
}
function showError(sender,args){
alert(args.get_message());
}
}