Archive
SharePoint 2013 – Read List Items using REST API
SharePoint 2013 introduced Rich REST endpoints, we can use this to query data asynchronously using jQuery/JavaScript.
Here is a sample code which can be used to read items from a SharePoint list
var siteUrl = window.location.protocol + "//" + window.location.host + _spPageContextInfo.siteServerRelativeUrl; jQuery.ajax({ url: siteUrl + "/_api/lists/getbytitle('ListTitle')/Items?$select Title", type: "GET", headers: { "accept": "application/json;odata=verbose", "content-type":"application/json;odata=verbose", "X-RequestDigest": jQuery("#__REQUESTDIGEST").val() }, success: function(d) { var stringData = JSON.stringify(d); var jsonObject = JSON.parse(stringData); var results = jsonObject.d.results; for(i = 0; i < results.length;i++) { console.log(results[i]["Title"]) } }, error: function() { console.log('fail'); } });
We are dynamically forming the site url using various tokens.
First we need to get the SharePoint list, for that we use REST method GetByTitle
and pass the list title. Then we are selecting the item Title
. You can add more fields by separating with comma.
The result is then converted to JSON object using JSON.Parse
method.
Finally a loop is used to iterate through the items.
JavaScript – Escaping quotes
While passing data through AJAX post we might want to escape quote characters. One option is to escape using JavaScript method, but this will encode the entire string. The simplest approach is using the replace method.
data.replace(/(['"])/g, "\\$1")
Javascript – Refresh or Reload Page
One line code that can refresh the page
document.location.reload(true);
Javascript – Global Error Handler
window.onerror = function(error, url, line) { var errorDetails = "Error Description = " + error; errorDetails += "\nUrl = " + url; errorDetails += "\nLine Number = " + line; alert(errorDetails); };