Sunday, August 3, 2014

Sharepoint 2013 Getting List Items using JSOM – Sharepoint-Hosted Application

1) Create Custom List in Sharepoint 2013(Office 2013 Account )

2) Copy & Paste below code in your App.js and deploy application

3) App.Js


// context: The ClientContext object provides access to
//      the web and lists objects.

var context = SP.ClientContext.get_current();

//Get the URI decoded SharePoint site url from the SPHostUrl parameter.
//https://XXX.sharepoint.com/TravelApp
var hostUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));

//https://XXX.sharepoint.com/TravelApp/TravelSystem
var appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));

var hostcontext = new SP.AppContextSite(context, hostUrl);
var web = hostcontext.get_web();
var lists = web.get_lists();


$(document).ready(function () {

    var scriptbase = hostUrl + "/_layouts/15/";
    $.getScript(scriptbase + 'SP.Runtime.js',
    function () {
        $.getScript(scriptbase + 'SP.js',
       function () {
           $.getScript(scriptbase + 'SP.RequestExecutor.js', execCrossDomainRequest);
       });
    });
});


function getQueryStringParameter(paramToRetrieve) {
    var params =
    document.URL.split("?")[1].split("&");
    var strParams = "";
    for (var i = 0; i < params.length; i = i + 1) {
        var singleParam = params[i].split("=");
        if (singleParam[0] == paramToRetrieve)
            return singleParam[1];
    }
}

function execCrossDomainRequest() {
    var context;
    var factory;
    var appContextSite;
    var mylist;
    context = new SP.ClientContext(appweburl);
    factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
    context.set_webRequestExecutorFactory(factory);
    appContextSite = new SP.AppContextSite(context, hostUrl);
    this.web = appContextSite.get_web();
    mylist = this.web.get_lists().getByTitle('Test');
    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml('<View><RowLimit>10</RowLimit></View>');
    var collListItem = mylist.getItems(camlQuery);
    context.load(mylist);
    context.load(collListItem);
    context.executeQueryAsync(
     Function.createDelegate(this, successHandler),
     Function.createDelegate(this, errorHandler)
    );

    function successHandler() {

        var listItemInfo = '';
        var listItemEnumerator = collListItem.getEnumerator();

        while (listItemEnumerator.moveNext()) {

            var oListItem = listItemEnumerator.get_current();

            listItemInfo += "<li style='height: 20px;'>" + oListItem.get_item('Title') + "</li>";
            document.getElementById("message").innerHTML = '<h1>' + mylist.get_title() + '</h1><br />';
            document.getElementById("message").innerHTML += listItemInfo.toString();
        }

    }
    function errorHandler() {
        alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    }

}

No comments:

Post a Comment