SharePoint Online: [Rest API & SharePoint App] How to access other web context

Required App permission to be setup in order to access the web, under AppManifest.xml

Example code snippet:

SP.AppContextSite is the core part to call from App to SharePoint


var hostweburl =
        decodeURIComponent(getQueryStringParameter("SPHostUrl"));

var appweburl =
        decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));

//Example: Get List Item
function getItems (listName, queryText, rowLimit) {
     var d = $.Deferred();
     var viewXml = '<View><Query>' + queryText + '</Query></View>';
     var query = {
         'query': {
            '__metadata': { 'type': 'SP.CamlQuery' },
            'ViewXml': viewXml
         }
     };
     //default limit
     var limit = 10;
     if (rowLimit)
        limit = rowLimit;
                
     var settings = {
        url: appweburl + "/_api/SP.AppContextSite(@target)/web/lists/GetByTitle('" + listName + "')/items?@target='" + hostweburl + "'&$top=" + limit,
        contentType: "application/json;odata=verbose",
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: function (data) {                                                
           d.resolve(data.d.results);
        },
        error: function (data) {
            d.reject(data);
        }
      };

      if (queryText) {
        settings["data"] = JSON.stringify(query);
      }

      $.ajax(settings);

      return d.promise();
}

When I click the “#” links, my browser automatically navigate to the top of the page

How to stop this?

  1. Uses “#_” instead of “#”, on some browser it just worked same as “_top”
  2. Use JavaScript to prevent this happening

Code snippet

For example if you have a link similar as below:

<a href=”#” class=”noAction”>Click me</a>

You can add the follow function to prevent the navigation:

$(“a.noAction”).click(function (e) {
//You can add additional function here for execution
e.preventDefault();
});