Pergunta

Estou desenvolvendo um aplicativo hospedado no SharePoint para o SharePoint 2013 (no Office365), mas tenho problemas para acessar listas em um aplicativo hospedado no SharePoint.

Meu código está imprimindo bem as listas, mas só me mostra a lista 'Aparências compostas' e as listas 'Galeria de páginas mestras', não consigo acessar as listas que criei no meu site sharepoint.

E quando tento acessar a lista de 'Contatos' (que existe no site do sharepoint onde implanto o aplicativo), ocorre esta exceção:

Lista 'Contatos' não existe no site com URL 'https://mysharepointsite-03ea186502297f.sharepoint.com/SPHostedApp12

Parece que meu aplicativo está sendo executado em outro site que não o meu site principal e é por isso que não consigo acessar as listas existentes no meu site principal...

Alguém sabe como resolver isso e acessar as listas existentes no site principal?

Muito obrigado !

Aqui está meu código App.js:

'use strict';

var gobbe = window.gobbe || {};

gobbe.Contacts;
gobbe.ContactList = function () {
    // private members
    var createItem = function (lname, fname, bphone) {
        var ctx = new SP.ClientContext.get_current();
        var list = ctx.get_web().get_lists().getByTitle('Contacts');
        ctx.load(list);
        var listItemCreationInfo = new SP.ListItemCreationInformation();
        var newContact = list.addItem(listItemCreationInfo);
        newContact.set_item('Last Name', lname);
        newContact.set_item('First Name', fname);
        newContact.set_item('Business Phone', bphone);
        newContact.update();
        ctx.executeQueryAsync(success, error);
    },
    readAll = function () {
        // Not implemented
    },
    readAllSuccess = function () {
        // Not implemented
    },
    updateItem = function () {
        // Not implemented
    },
    updateItem = function (id, lname, fname, bphone) {
        // Not implemented
    },
    removeItem = function (id) {
        // Not implemented
    },
    success = function () {
        readAll();
    },
    error = function (sender, args) {
        alert(args.get_message());
    }

    // public interface
    return {
        createContact: createItem,
        updateContact: updateItem,
        deleteContact: removeItem
    }
}();

gobbe.Collections = function () {
    // private members
    var site,
        listCollection,

        getListCollection = function () {
            var ctx = new SP.ClientContext.get_current();
            site = ctx.get_web();
            ctx.load(site);
            listCollection = site.get_lists();
            ctx.load(listCollection,     'Include(Title,Id,Fields.Include(Title,Description))');
        ctx.executeQueryAsync(success, failure);
        },

        success = function () {
            var html = [];

            // List Information
            html.push('<ul>');
            var listEnumerator = listCollection.getEnumerator();
            while (listEnumerator.moveNext()) {
                // List Title
                html.push('<li>');
                html.push(listEnumerator.get_current().get_title());
                html.push('<ul>');

                // Fields Names
                var fieldEnumerator =     listEnumerator.get_current().get_fields().getEnumerator();
                while (fieldEnumerator.moveNext()) {
                    html.push('<li>');
                    html.push(fieldEnumerator.get_current().get_title());
                    html.push('</li>');
                }

                html.push('</ul></li>')
            }
            html.push('</ul>');

            // Show results
            $('#displayDiv').html(html.join(''));
        },

        failure = function (sender, args) {
            alert(args.get_message());
        }

    // public interface
    return {
        execute: getListCollection
    }
}();

$().ready(function () {
    // Show lists
    gobbe.Collections.execute();

    // Try to add a contact
    gobbe.ContactList.createContact('Cox', 'Brian', '555-555-5555');
    alert('Contact Created!');

    // Update it
    gobbe.ContactList.updateContact(1, 'Cox', 'Brian', '111-111-1111');
    alert('Contact Updated!');

    // Delete it
    gobbe.ContactList.deleteContact(1);
    alert('Contact Deleted!');
});
Foi útil?

Solução

Os aplicativos funcionam em um domínio diferente em comparação ao seu host da web.Portanto, é uma chamada entre domínios quando você tenta acessar alguma lista que reside em seu host a partir do seu aplicativo.Normalmente os navegadores não permitem fazer essas chamadas entre domínios por motivos de segurança.Porém, em aplicativos, para interagir com o host web, existe uma biblioteca chamada SP.RequestExecutor.js, que é uma biblioteca entre domínios que você pode usar para fazer essas chamadas.Dê uma olhada nos links a seguir que o ajudarão a fazer essas chamadas entre domínios para acessar dados da web do host dentro de um aplicativo da web.

http://msdn.microsoft.com/en-in/library/fp179927.aspx

http://www.mavention.com/blog/sharePoint-app-reading-data-from-host-web

http://blogs.msdn.com/b/officeapps/archive/2012/11/29/solving-cross-domain-problems-in-apps-for-sharepoint.aspx

Espero que ajude.

Outras dicas

Parece que você se esqueceu de conceder permissões ao seu aplicativo:A lista 'Contatos' não existe no site com URL.

Ao instalar um aplicativo, serão solicitados os direitos de acesso a uma biblioteca ou lista específica, por exemplo.

Você terá que adicionar algo assim ...Exemplo da aparência da marcação em um manifesto de aplicativo:

<AppPermissionRequests> <AppPermissionRequest Scope="http://sharepoint/content/sitecollection/web/list" Right="Write"/></AppPermissionRequests>

Para acessar a lista do Host web, você precisaria confiar nos "tokens padrão" e, em seguida, usar JSOM ou REST APi para acessar os dados.

 //Get the URI decoded URLs.
                hostweburl =
                    decodeURIComponent(
                        getQueryStringParameter("SPHostUrl")
                );
                appweburl =
                    decodeURIComponent(
                        getQueryStringParameter("SPAppWebUrl")
                );

Então você poderia usar algo assim:

 // Initialize the RequestExecutor with the app web URL.
                executor = new SP.RequestExecutor(appweburl);

                // Issue the call against the host web.
                // To get the title using REST we can hit the endpoint:
                //      app_web_url/_api/SP.AppContextSite(@target)/web/title?@target='siteUrl'
                // The response formats the data in the JSON format.
                // The functions successHandler and errorHandler attend the
                //      success and error events respectively.
                executor.executeAsync(
                    {
                        url:
                            appweburl +
                            "/_api/SP.AppContextSite(@target)/web/title?@target='" +
                            hostweburl + "'",
                        method: "GET",
                        headers: { "Accept": "application/json; odata=verbose" },
                        success: successHandler,
                        error: errorHandler
                    }
                );
Licenciado em: CC-BY-SA com atribuição
Não afiliado a sharepoint.stackexchange
scroll top