CustomCodes‎ > ‎

Getting sharepoint list data using REST and CAML & Return type AJAX

$(document).ready(function () {
    try {
        // Your list name comes here:
        var ListName = 'MY_LIST_NAME';
        // Your CAML query comes here to filter data:
        var Caml = "<View Scope='RecursiveAll'><Query><OrderBy><FieldRef Name='Title' Ascending='False' /></OrderBy></Query></View>";        
         getData(ListName, Caml).done(function(data){
         $.each(data.d.results, function (index, item) {
                alert(item.Title); // Internal name of field should be used to retrieve metadata of list items.
            });    
         });      
    }
    catch (error) {
        console.log('Error in docReady: ' + error.message);
    }
});
 
// Function to get and use data :
function getData(strListTitle, viewXml) {
    var currentSite = _spPageContextInfo.webAbsoluteUrl;
    return $.ajax({
        type: "POST",
        async: true,
        headers: {
            "accept": "application/json;odata=verbose",
            "content-type": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        // $top5 has been used to get only 5 values from top.
        url: currentSite + '/_api/web/Lists/GetByTitle(\''+strListTitle +'\')/GetItems([email protected])?$top=5&@v1={"ViewXml":"' + viewXml + '"}'      
    });
}
Comments