2017-10-28 95 views
1

我從JSON文件加載我上的document.ready()表如下加載HTML表

文檔加載....

$(document).ready(function() { 
     getSummaryData(function (data1) { 
      var dataarray=new Array(); 
      dataarray.push(data1); 


      $('#summaryTable').DataTable({ 
       data: dataarray, 
       "columns": [ 
       --- 
       --- 

,並從文件中檢索數據如下

function getSummaryData(cb_func1) { 
    $.ajax({ 
     url: "data/summary.json", 
     success: cb_func1 
    }); 
    console.log(cb_func1) 
} 

這實際上是加載虛擬數據,所以我可以弄清楚如何正確加載表等。這工作正常。

它下面 1.頁面加載 2.從文件中讀取數據 3.填充表

在現實中,數據將不會從文件加載,但將從XHR響應返回,但我不能弄清楚 如何將它們連接在一起。用例是

  1. POST通過XMLHttpRequest
  2. 獲取響應
  3. 填入表(相同的數據格式文件)

我會後文件如下文件...

<script> 
    var form = document.getElementById('form'); 
    var fileSelect = document.getElementById('select'); 
    var uploadButton = document.getElementById('upload'); 

    --- 
    form.onsubmit = function(event) { 
     event.preventDefault(); 
    --- 
--- 
var xhr = new XMLHttpRequest(); 

// Open the connection. 
xhr.open('POST', 'localhost/uploader', true);  

    // handler on response 
    xhr.onload = function() { 
     if (xhr.status === 200) { 

      console.log("resp: "+xhr); 
      console.log("resptxt: "+xhr.responseText); 

      //somehow load table with xhr.responseText 

     } else { 
      alert('ooops'); 
     } 
    }; 

    // Send the Data. 
    xhr.send(formData); 

所以理想情況下,我需要在表中或類似的空行,直到有人上傳文件,然後填充表wi迴應。

任何幫助非常感謝。

+0

你在使用什麼服務器? – Hunter

回答

0
var xhr1 = new XMLHttpRequest(); 
xhr1.open('POST', "youruploadserver.com/whatever", true); 
xhr1.onreadystatechange = function() { 
    if (this.status == 200 && this.readyState == 4) { 
     console.log(this.responseText); 
     dostuff = this.responseText; 
    };//end onreadystate 
xhr1.send(); 

它看起來大部分是正確的,你想this.readyState == 4在那裏。你的問題是什麼,如何從響應中填充表格? 這也取決於你將如何發送數據以及服務器如何解析數據,看起來像你想使用一個聰明的json格式。 JSON.stringify(formdata)然後確保您的服務器將其解析爲json對象根據您使用的服務器使用body-parser。然後你JSON.stringify()對象發回它。