Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var EmployeesAsJson = [
- {
- __metadata: {
- type: 'SP.Data.EmployeesListItem'
- },
- FirstName: 'User1',
- LastName: 'Test1',
- Email: 'User1.Test1@email.com'
- },
- {
- __metadata: {
- type: 'SP.Data.EmployeesListItem'
- },
- FirstName: 'User2',
- LastName: 'Test2',
- Email: 'User2.Test2@email.com'
- },
- {
- __metadata: {
- type: 'SP.Data.EmployeesListItem'
- },
- FirstName: 'User3',
- LastName: 'Test3',
- Email: 'User3.Test3@email.com'
- }
- 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;
- // for 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('Employees')'
- + '/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 + '--');
- // generate the body of the batch
- var batchBody = batchContents.join('rn');
- // create the request endpoint
- var endpoint = _spPageContextInfo.webAbsoluteUrl
- + '/_api/$batch';
- // batches need a specific header
- 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) {
- alert("Successfully saved a batch request");
- },
- fail: function (error) {
- alert('.. create employee FAIL ', error);
- }
- });
Add Comment
Please, Sign In to add comment