пакетный отдых позвоните в sharepoint онлайн - PullRequest
0 голосов
/ 17 января 2020

Я пытаюсь понять, как работают вызовы пакетного отдыха.

Я не смог найти простой пример для inte rnet. Я нашел примеры из https://github.com/andrewconnell/sp-o365-rest, но не могу запустить эти примеры или пока не знаю как. Я предполагаю, что вам нужно развернуть приложение на сайте sharepoint.

Учитывая это, я просто ищу самый простой пример добавления элемента списка и обновления списка в пакетном / пакетном режиме. Также, если кто-нибудь знает, как я могу сделать приложение из этого git для запуска, будет очень признателен.

Спасибо.

1 Ответ

0 голосов
/ 20 января 2020

Проект github - это проект надстройки, поэтому вам нужно развернуть проект надстройки, а затем использовать его.

Здесь можно проверить скрипт ниже .

Мой результат теста в этой теме

(function () {
    jQuery(document).ready(function () {
       jQuery("#btnFetchEmployees").click(function () {
            addEmployees();
        });
    });
})();
function addEmployees() {
    var employeesAsJson = undefined;
    employeesAsJson = [
            {
                __metadata: {
                    type: 'SP.Data.EmployeeInfoListItem'
                },
                Title: 'Geetanjali',
                LastName: 'Arora',
                Technology: 'SharePoint'
            },
            {
                __metadata: {
                    type: 'SP.Data.EmployeeInfoListItem'
                },
                Title: 'Geetika',
                LastName: 'Arora',
                Technology: 'Graphics'
            },
            {
                __metadata: {
                    type: 'SP.Data.EmployeeInfoListItem'
                },
                Title: 'Ashish',
                LastName: 'Brajesh',
                Technology: 'Oracle'
            }
    ];

    addEmployeeInfoBatchRequest(employeesAsJson);
}

function generateUUID() {
    var d = new Date().getTime();
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c == 'x' ? r : (r & 0x7 | 0x8)).toString(16);
    });
    return uuid;
};

function addEmployeeInfoBatchRequest(employeesAsJson) {
    // generate a batch boundary
    var batchGuid = generateUUID();
    // creating the body
    var batchContents = new Array();
    var changeSetId = generateUUID();
    // get current host
    var temp = document.createElement('a');
    temp.href = _spPageContextInfo.webAbsoluteUrl;
    var host = temp.hostname;
    // iterate through each employee
    for (var employeeIndex = 0; employeeIndex < employeesAsJson.length; employeeIndex++) {

        var employee = employeesAsJson[employeeIndex];

        // create the request endpoint
        var endpoint = _spPageContextInfo.webAbsoluteUrl
                       + '/_api/web/lists/getbytitle(\'EmployeeInfo\')'
                       + '/items';

        // create the changeset
        batchContents.push('--changeset_' + changeSetId);
        batchContents.push('Content-Type: application/http');
        batchContents.push('Content-Transfer-Encoding: binary');
        batchContents.push('');
        batchContents.push('POST ' + endpoint + ' HTTP/1.1');
        batchContents.push('Content-Type: application/json;odata=verbose');
        batchContents.push('');
        batchContents.push(JSON.stringify(employee));
        batchContents.push('');
    }
    // END changeset to create data
    batchContents.push('--changeset_' + changeSetId + '--');


    // batch body
    var batchBody = batchContents.join('\r\n');

    batchContents = new Array();

    // create batch for creating items
    batchContents.push('--batch_' + batchGuid);
    batchContents.push('Content-Type: multipart/mixed; boundary="changeset_' + changeSetId + '"');
    batchContents.push('Content-Length: ' + batchBody.length);
    batchContents.push('Content-Transfer-Encoding: binary');
    batchContents.push('');
    batchContents.push(batchBody);
    batchContents.push('');

    // create request in batch to get all items after all are created
    endpoint = _spPageContextInfo.webAbsoluteUrl
                  + '/_api/web/lists/getbytitle(\'EmployeeInfo\')'
                  + '/items?$orderby=Title';


    batchContents.push('--batch_' + batchGuid);
    batchContents.push('Content-Type: application/http');
    batchContents.push('Content-Transfer-Encoding: binary');
    batchContents.push('');
    batchContents.push('GET ' + endpoint + ' HTTP/1.1');
    batchContents.push('Accept: application/json;odata=verbose');
    batchContents.push('');

    batchContents.push('--batch_' + batchGuid + '--');

    batchBody = batchContents.join('\r\n');

    // create the request endpoint
    var endpoint = _spPageContextInfo.webAbsoluteUrl + '/_api/$batch';

       var batchRequestHeader = {
        'X-RequestDigest': jQuery("#__REQUESTDIGEST").val(),
        'Content-Type': 'multipart/mixed; boundary="batch_' + batchGuid + '"'
    };

    // create request
    jQuery.ajax({
        url: endpoint,
        type: 'POST',
        headers: batchRequestHeader,
        data: batchBody,
        success: function (response) {

            var responseInLines = response.split('\n');


        $("#tHead").append("<tr><th>First Name</th><th>Last Name</th><th>Technology</th></tr>");

            for (var currentLine = 0; currentLine < responseInLines.length; currentLine++) {
                try {

                    var tryParseJson = JSON.parse(responseInLines[currentLine]);

                    $.each(tryParseJson.d.results, function (index, item) {

                        $("#tBody").append("<tr><td>" + item.Title + "</td><td>" + item.LastName + "</td><td>" + item.Technology + "</td></tr>");

                    });


                } catch (e) {

                }
            }
        },
        fail: function (error) {

        }
    });
}
...