簡體   English   中英

如何將 Ajax 數據發布到您的服務器以更新 SharePoint 列表數據

[英]How to post Ajax Data to your server to update SharePoint list data

我已經在這個 DataTable 上工作了一段時間,除了最后一件事之外,我擁有我需要的所有功能。 現在,我的表從 AJAX“GET”請求中讀取 SharePoint 列表數據,並根據父/子行對其進行填充和組織。

我需要我的 DataTable 做的最后一個功能是創建一個按鈕,允許您將新行添加到表中,然后它會根據“程序和可交付成果”類別將其自動分類到正確的子行中。 這樣做之后,我想讓 DataTable 將數據發送到相應的 SharePoint 列表,這是否可以通過 AJAX“POST”請求完成?

我怎樣才能做到這一點? 我現在完全迷失了。

這是我的代碼:

 function loadData() { //Initializing the AJAX Request function to load in the external list data from different subsites //create an array of urls to run through the ajax request instead of having to do multiple AJAX Requests var urls = ["url1","url2","url3","url4","url5","url6","url7","url8"]; for (i=0; i < urls.length; i++) { //for loop to run through the AJAX until all URLs have been reached $.ajax({ url: urls[i], 'headers': { 'Accept': 'application/json;odata=nometadata' }, success: function (data) { // success function which will then execute "GETTING" the data to post it to a object array (data.value) data = data; var table = $('#myTable').DataTable(); table.rows.add( data.value ).draw(); } }); } } $(document).ready(function() { var collapsedGroups = {}; var top = ''; var parent = ''; var table = $('#myTable').DataTable( { "columns": [ { "data": "Program", visible: false }, { "data": "Deliverable", visible: false }, { "data": "To" }, { "data": "Date" }, { "data": "Approved" }, { "data": "Notes" } ], dom: "<'row'<'col-sm-12 col-md-10'f><'col-sm-12 col-md-2'B>>" + "<'row'<'col-sm-12'tr>>" + "<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>", buttons: [{ extend: 'collection', className: "btn-dark", text: 'Export', buttons: [{ extend: "excel", className: "btn-dark" }, { extend: "pdf", className: "btn-dark" }, { extend: "print", className: "btn-dark" }, ], }], order: [[0, 'asc'], [1, 'asc'] ], rowGroup: { dataSrc: [ 'Program', 'Deliverable' ], startRender: function (rows,group,level){ var all; if (level === 0) { top = group; all = group; } else if (level === 1) { parent = top + group; all = parent; // if parent collapsed, nothing to do if (!collapsedGroups[top]) { return; } } else { // if parent collapsed, nothing to do if (!collapsedGroups[parent]) { return; } all = top + parent + group; } var collapsed = !collapsedGroups[all]; console.log('collapsed:', collapsed); rows.nodes().each(function(r) { r.style.display = collapsed ? 'none' : ''; }); //Add category name to the <tr>. return $('<tr/>') .append('<td colspan="8">' + group + ' (' + rows.count() + ')</td>') .attr('data-name', all) .toggleClass('collapsed', collapsed); } } } ); loadData(); $('#myTable tbody').on('click', 'tr.dtrg-start', function () { var name = $(this).data('name'); collapsedGroups[name] = !collapsedGroups[name]; table.draw(false); }); var table = $('#example').DataTable( { var urls = ["url1","url2","url3","url4","url5",...]; for (i=0; i < urls.length; i++) { ajax: { url: urls[i], method: "POST", data: function( ) { return dataToSend; } }, } } ); } ); } );
 .btn-dark { color: #fff; background-color: #343a40; border-color: #343a40; } div.container { min-width: 980px; margin: 0 auto; } .header { padding: 10px; text-align: center; } body { font: 90%/1.45em "Helvetica Neue", HelveticaNeue, Verdana, Arial, Helvetica, sans-serif; margin: 0; padding: 0; color: #333; background-color: #fff; } div.dt-button-collection { position: static; }
 <link rel ="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css"/> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.js"></script> <script src="https://momentjs.com/downloads/moment.min.js"></script> <script src="https://cdn.datatables.net/buttons/1.6.2/js/dataTables.buttons.min.js"></script> <script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.flash.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script> <script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.html5.min.js"></script> <script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.print.min.js"></script> <script src="https://cdn.datatables.net/rowgroup/1.1.2/js/dataTables.rowGroup.min.js"></script> <script src="https://cdn.datatables.net/buttons/1.6.3/js/buttons.bootstrap4.min.js"></script> <script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap4.min.js"></script> <script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script> <link rel ="stylesheet" href="https://cdn.datatables.net/rowgroup/1.1.2/css/rowGroup.bootstrap4.min.css"/> <link rel ="stylsheet" href="https://cdn.datatables.net/1.10.21/css/dataTables.bootstrap4.min.css"/> <link rel ="stylesheet" href="https://cdn.datatables.net/buttons/1.6.3/css/buttons.bootstrap4.min.css"/> <h1><strong>Deliverables</strong></h1> <p><strong>Click the Program/Deliverable names to Collapse/Expand the rows</strong></p> </div> <div class ="container"> <table id="myTable" class="table table-bordered" cellspacing="0" width="100%"> <thead class="thead-dark"> <tr> <th>Program</th> <th>Deliverable</th> <th>To</th> <th>Date</th> <th>Approved</th> <th>Notes</th> </tr> </thead> <tfoot class="thead-dark"> <tr> <th>Program</th> <th>Deliverable</th> <th>To</th> <th>Date</th> <th>Approved</th> <th>Notes</th> </tr> </tfoot> </table> </div>

我相信這應該是將數據從 DataTable 發送到 SharePoint 列表的正確函數,但它目前沒有用,因為我無法弄清楚如何向數據表添加新行/數據。

function sendData() {
    var urls = ["url1","url2","url3","url4","url5","url6","url7","url8"];
        
    var data1 = {
           Program: 'Please provide the Program name here',
           Deliverable: 'Please provide the type of deliverable here',
           To: 'Please provide the recipients email here',
           Date: 'Please provide the submission date here',
           Approved: 'Please provide where or not the deliverable has been approved here',
           Notes: Please provide notes about the deliverable here'
    };
     $.ajax({
        for (i=0; i < urls.length; i++) {
        $.ajax({
                   url: urls[i],
                   method: "POST",
                                 data: JSON.stringify(data),
                   headers: { "Accept": "application/json; odata=verbose",
                                   "X-RequestDigest": $("#__REQUESTDIGEST").val()                                 
                   },
                   success: function (data) {
                              alert('Item added successfully');
                  },
                  error: function (error) {
                      alert("Error: "+ JSON.stringify(error));
                 }
          });
        }
    });
}

您可以使用標准的jQuery ajax data選項從 DataTales ajax 請求中將數據發布到服務器 - 但稍作修改以符合 DataTables 使用它的方式。

此處記錄了用於將動態構建的數據發送到服務器的 DataTables 語法。 方法是這樣的:

ajax: {
  type: "POST", // or "GET"
  url: "http://whatever.com/endpoint",
  data: function () {
    return dataToSend; // dataToSend is just my JS variable
  }
}

注意這里的data選項是一個函數,它返回要發送到服務器的數據。

變量dataToSend的數據可以通過多種方式准備,具體取決於您的特定需求和上下文。

例如,它可以是標准 HTML <form> - 所有表單輸入字段的值。 在這種情況下,您可能希望將表單的數據轉換為 JSON(例如,使用 jQuery 的$.serialize()函數或$.serializeArray()函數。

如果你的 JavaScript 代碼中已經有一個 JSON 對象,你可以通過設置 ajax contentType和字符串化你的 JSON 來發送它 - 像這樣:

ajax: {
  type: "POST", // or "GET"
  url: "http://whatever.com/endpoint",
  data: function () {
    contentType: "application/json",
    return JSON.stringify(dataToSend);
  }
}

(否則默認內容類型將是application/x-www-form-urlencoded 。)

這是一個示例,其中我們在與 DataTable 相同的頁面中有一個簡單的表單:

<form id ="formOne">
    <input id="fieldOne" type="text" name="fieldOne"></input>
    <input id="fieldTwo" type="text" name="fieldTwo"></input>
    <input type="submit" value="Submit">
</form>

該表單有兩個輸入字段和一個提交按鈕。

DataTable ajax部分如下:

var table = $('#example').DataTable( {
  ajax: {
    url: "http://whatever.com/endpoint",
    method: "POST",
    data: function( ) {
      return dataToSend;
    }
  },
  // other items not shown
} );

當頁面加載時,表格會照常顯示。

如果用戶填寫表單並點擊提交按鈕,則此操作被以下代碼攔截:

var dataToSend;

$( "#formOne" ).on( "submit", function( event ) {
  event.preventDefault(); // stops the standard form submission from happening
  dataToSend = $( "#formOne" ).serializeArray();
  console.log( dataToSend );
  table.ajax.reload(); // calls the DataTables ajax request again
});

當然,由服務器來處理這個請求中的結果數據。 因為我的示例是POST請求,所以這將涉及訪問表單參數數據的服務器端代碼。 您如何執行此操作取決於您使用的服務器端框架。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM