Lately I've been working with SharePoint a lot and creating functions to read data from lists and manipulate / display it to the user. Below are two generic JS / jQuery functions that I created to do this.
I've explained the parameters so hopefully you will find it useful.
// inListSiteURL is the base URL of the SharePoint site... such as https://somespsite.somedomain.com or https://somespsite.somedoamin.com/someSubSite
// inListTitle is the title of the SharePoint list
// inHaveResultsFunction is the function to call when data is found
// inNoResultsFunciton is the function to call when no data is found
// inFilter is the filter to use... maybe something like "?$select=Title,URL&$top=100&$filter=Editor/Id%20eq%20123&$orderby=Title asc"... you can leave this blank if you want
// inFinalFunction is the function to call after all results
function spGetListData(inListSiteURL, inListTitle, inHaveResultsFunction, inNoResultsFunction, inFilter, inFinalFunction)
{
try {
var callURL = inListSiteURL + "/_api/web/lists/GetByTitle('" + inListTitle + "')/items" + inFilter;
spGetRestDataCall(callURL, inHaveResultsFunction, inNoResultsFunction, null, inFinalFunction);
} catch(err) {
}
} // function spGetListData
// this function is a 'generic' ajax call used by the other functions to simplify the code
// inURL is the URL to the SharePoint list to retrieve data from
// inSuccessFunction is the function to call when data is returned
// inNoResultFunction is the function to call when no data is returned
// inErrorFunction is the function to call when an error is encountered
// inFinalFunction is the function to call when after all the data is processed
function spGetRestDataCall(inURL, inSuccessFunction, inNoResultFunction, inErrorFunction, inFinalFunction)
{
var spRestContentType = "application/json;odata=verbose"; // you should not have to change this
$.ajax({
url: inURL,
method: "GET",
processData: false,
contentType: spRestContentType,
headers: { "Accept": spRestContentType },
success: function (data) {
try {
if (data.d.results.length == 0) {
if (inNoResultFunction !== null) {
inNoResultFunction();
}
} else {
$.each(data.d.results, function(index, item){
inSuccessFunction(index,item);
});
if (inFinalFunction !== null) {
inFinalFunction();
}
}
} catch(err) {
inSuccessFunction(data.d);
}
},
error: function (data) {
//console.log(JSON.stringify(data));
if (inErrorFunction !== null) {
inErrorFunction(data);
}
}
});
} // function spGetRestDataCall
Sunday, June 18, 2017
SharePoint jQuery generic call to get rest data
Subscribe to:
Comments (Atom)