Guest User

Untitled

a guest
Feb 15th, 2018
319
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.69 KB | None | 0 0
  1. var EmployeesAsJson = [
  2. {
  3. __metadata: {
  4. type: 'SP.Data.EmployeesListItem'
  5. },
  6. FirstName: 'User1',
  7. LastName: 'Test1',
  8. Email: 'User1.Test1@email.com'
  9. },
  10. {
  11. __metadata: {
  12. type: 'SP.Data.EmployeesListItem'
  13. },
  14. FirstName: 'User2',
  15. LastName: 'Test2',
  16. Email: 'User2.Test2@email.com'
  17. },
  18. {
  19. __metadata: {
  20. type: 'SP.Data.EmployeesListItem'
  21. },
  22. FirstName: 'User3',
  23. LastName: 'Test3',
  24. Email: 'User3.Test3@email.com'
  25. }
  26.  
  27.  
  28.  
  29. var batchGuid = generateUUID();
  30.  
  31. // creating the body
  32. var batchContents = new Array();
  33. var changeSetId = generateUUID();
  34.  
  35. // get current host
  36. var temp = document.createElement('a');
  37. temp.href = _spPageContextInfo.webAbsoluteUrl;
  38. var host = temp.hostname;
  39.  
  40. // for each employee...
  41. for (var employeeIndex = 0; employeeIndex < employeesAsJson.length; employeeIndex++) {
  42.  
  43. var employee = employeesAsJson[employeeIndex];
  44.  
  45. // create the request endpoint
  46. var endpoint = _spPageContextInfo.webAbsoluteUrl
  47. + '/_api/web/lists/getbytitle('Employees')'
  48. + '/items';
  49.  
  50. // create the changeset
  51. batchContents.push('--changeset_' + changeSetId);
  52. batchContents.push('Content-Type: application/http');
  53. batchContents.push('Content-Transfer-Encoding: binary');
  54. batchContents.push('');
  55. batchContents.push('POST ' + endpoint + ' HTTP/1.1');
  56. batchContents.push('Content-Type: application/json;odata=verbose');
  57. batchContents.push('');
  58. batchContents.push(JSON.stringify(employee));
  59. batchContents.push('');
  60. }
  61. // END changeset to create data
  62. batchContents.push('--changeset_' + changeSetId + '--');
  63.  
  64. // generate the body of the batch
  65. var batchBody = batchContents.join('rn');
  66.  
  67. // create the request endpoint
  68. var endpoint = _spPageContextInfo.webAbsoluteUrl
  69. + '/_api/$batch';
  70.  
  71. // batches need a specific header
  72. var batchRequestHeader = {
  73. 'X-RequestDigest': jQuery("#__REQUESTDIGEST").val(),
  74. 'Content-Type': 'multipart/mixed; boundary="batch_' + batchGuid + '"'
  75. };
  76.  
  77. // create request
  78. jQuery.ajax({
  79. url: endpoint,
  80. type: 'POST',
  81. headers: batchRequestHeader,
  82. data: batchBody,
  83. success: function (response) {
  84. alert("Successfully saved a batch request");
  85. },
  86. fail: function (error) {
  87. alert('.. create employee FAIL ', error);
  88. }
  89. });
Add Comment
Please, Sign In to add comment