Pregunta

Estoy desarrollando una aplicación de SharePoint-Hosted para SharePoint 2013 (en Office365), pero tengo problemas para acceder a las listas dentro de una aplicación de SharePoint-Hosted.

Mi código está bien imprimiendo las listas, pero solo me muestra la lista 'mirada compuesta' y las listas 'Galería de página maestra', no puedo acceder a las listas que he creado en mi sitio de SharePoint.

y cuando intento acceder a la lista 'Contactos' (que existe en el sitio de SharePoint donde implemento la aplicación), obtuve esta excepción:

Lista 'Contactos' no existe en el sitio con URL ' https://mysharepointsite-03ea186502297f.sharepoint.com/sphostedapp12

Parece que mi aplicación se ejecuta desde otro sitio que mi sitio principal, y por eso no puedo acceder a las listas existentes desde mi sitio web principal ...

¿Alguien sabe cómo resolver esto y acceder a las listas existentes en el sitio principal?

¡Gracias mucho!

Aquí está mi 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!');
});

¿Fue útil?

Solución

Las aplicaciones funcionan en un dominio diferente en comparación con su web host. Por lo tanto, es una llamada de dominio cruzado cuando intenta acceder a una lista que reside en su web anfitriona de su web. Normalmente, los navegadores no permiten que estas llamadas de dominio cruzado por razones de seguridad. Sin embargo, en aplicaciones, para interactuar con la Web de acogida, hay una biblioteca llamada SP.RequeStexecutor.js, que es una libarada de dominio cruzado que puede usar para realizar estas llamadas. Eche un vistazo a los siguientes enlaces que lo ayudarán a realizar estas llamadas de dominio cruzado para acceder a los datos web de host dentro de una aplicación web.

http://msdn.microsoft.com/en-in/library/ FP179927.ASPX

http://www.mavention.com/ Blog / SharePoint-App-Reading-Data-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 ayude.

Otros consejos

Suena como si olvidó darle a los permisos de su aplicación: la lista 'Contactos' no existe en el sitio con URL.

Cuando instala una aplicación, se le pedirá que los derechos accedan a una biblioteca o lista específicos, por ejemplo.

Tendrás que agregar algo como este ... Ejemplo de cómo se ve el marcado en un manifiesto de aplicación:

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

Para acceder a la lista desde la web del host, debe confiar en los "tokens estándar" y luego usar el EITE JSOM o API de descanso para acceder a los datos.

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

entonces podrías usar algo como esto:

 // 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 bajo: CC-BY-SA con atribución
scroll top