通过SharePoint列表中的ID获取多个列表项

时间:2019-02-27 11:15:23

标签: sharepoint-2013

我正在尝试从SharePoint列表中检索列表项目,但是我的问题是我想按ID检索最后四个项目,但我不知道如何继续使用JSOM。 有人可以帮我写一些CAML代码以实现该功能吗?

var ctx = new SP.ClientContext.get_current();
var web = ctx.get_web();

//Geting reference to the list
var olist = web.get_lists().getByTitle('Configs');
var oitem = olist.getItemById(1);
//get Title,id,ConfigItem fields
ctx.load(oitem, "Title", "Id", "ConfigItem");
ctx.executeQueryAsync(function () {

    alert(oitem.get_item("Title"));
    alert(oitem.get_item("ConfigItem"));

}, function (a, b) {
    alert(b.get_message());
});

2 个答案:

答案 0 :(得分:1)

您可以将rest api与order by和$ top选项配合使用。

/_api/web/lists/getbytitle('chart')/items?$select=ID,Title&$orderby= ID desc&$top=4

Rest api获取列表项。

$.ajax({
                url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('chart')/items?$select=ID,Title&$orderby= ID desc&$top=4",
                type: "GET",                
                headers:
                {
                    "Accept": "application/json;odata=verbose",
                    "Content-Type": "application/json;odata=verbose"                    
                },                
                success: function (data) {                    
                    for (var i = 0; i < data.d.results.length; i++) {
                        var item = data.d.results[i];
                        //to do
                    }                        
                },
                error: function (data) {
                    console.log(data.responseJSON.error);
                }
            });  

答案 1 :(得分:0)

这是使用CamlQuery的JSOM解决方案。

var ctx = new SP.ClientContext.get_current();
var web = ctx.get_web();

var query = new SP.CamlQuery()
query.set_viewXml("<View><Query><OrderBy><FieldRef Name='ID' Ascending='FALSE' /></OrderBy></Query><RowLimit>4</RowLimit></View>")

var list = web.get_lists().getByTitle('Configs');
var items = list.getItems(query, "ID", "Title", "FirstName", "LastName", "Level", "Grade", "Date");
var dictionary = [];

ctx.load(items);
ctx.executeQueryAsync(function () {
    var enumerator = items.getEnumerator();
    while (enumerator.moveNext()) {
        var item = enumerator.get_current();
        dictionary.push({
            title: item.get_item("Title"),
            firstName: item.get_item("FirstName"),
            lastName: item.get_item("LastName"),
            level: item.get_item("Level"),
            grade: item.get_item("Grade"),
            date: item.get_item("Date"),
        });
    }
}, function (a, b) {
    alert(b.get_message());
});