Read List Items using REST API

1 comment
Hi All,

In a following post we will see how to read List Items using REST API and bind it to a Page.

Please find the below code snippet.It is a self explanatory.


<html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script type="text/javascript">
     var context;
     var web;
        $(document).ready(function () {
        SP.SOD.executeFunc('sp.js', 'SP.ClientContext', FunctionReady);
                  FunctionReady();
        });

function FunctionReady()
{
  context= new SP.ClientContext.get_current();
        web=context.get_web();
        context.load(web);
        context.executeQueryAsync(onRequestSuccess,onRequestFailure);
}
//get the current web context
function onRequestSuccess()
{
 // Get the current web Url
  var QueryUrl=web.get_url();
  MyfirstRest(QueryUrl);
}
function onRequestFailure(sender,args)
{
  alert("Error Occured:"+args.get_message());
}
       // My function which is used to get the List Collection . Currency is my List Name.
        function MyfirstRest(webUrl) {       
             //Creating Url
            var queryUrl = webUrl+"/_api/lists/getbytitle('Currency')/items";
            $.ajax({
                url: queryUrl,
                method: "GET",
                headers: { "Accept": "application/json; odata=verbose" },
                success: onQuerySuccess,
                error: onQueryError
            });
        }

        function onQuerySuccess(data) {
            var r = data.d.results;
             //Creating a table structure
              $("#myResult").append('<table>')
            $("#myResult").append('<tr><td style="font-weight:italic">Currency</td></tr>')
                      //Looping Jason data and binding to div 
                        $.each(r,function(index,Loaddata){
                                                $("#myResult").append('<tr>')
                                                $("#myResult").append('<td>'+Loaddata.Title+ '</td>') 
                                               $("#myResult").append('</tr>')
                             });
                   
            $("#myResult").append('</table>')
        }

       function onQueryError(error) {
            alert("Error: "+error.statusText);
        }
    </script>
</head>
<body>
<div id="myResult">
</div>
</body>
</html>



Final Out put will be looks as follows:


Note: As part of demo , I have place Content Editor Webpart in my page and mapped this file with it.

Update: Instead of Writing separate function to get the current Web, We can use url=_spPageContextInfo.webAbsoluteUrl; to get the Current Web URL in the above Code.

Related Post

1 comment:

  1. Where is the Rest API in this code? This is JSOM, not REST API. Bad Impression

    ReplyDelete