2016-03-21 47 views
0

我想連接字符串以將它傳遞給數據表,我從servlet獲取數據,當我把靜態字符串的作品,但我不知道如何處理它使用循環,因爲它是動態數據如何使用javascript呈現數據集中的dataSet

function getMsgHandler(responseTxt, statusTxt, xhr) { 
    alert(responseTxt); 
    if (statusTxt === "success") { 
     products = responseTxt; 
     var s = ""; 
     for (i = 0; i < products.length; i++) { 
      if (i === 0) { 
       s = s + '[' + products[i].productID + ', "' + products[i].name + '", "' + products[i].description + '", "' + products[i].img + '", ' + products[i].price + ' ]'; 
      } else { 
       s = s + ', [' + products[i].productID + ', "' + products[i].name + '", "' + products[i].description + '", "' + products[i].img + '", ' + products[i].price + ']'; 
      } 
     } 
     dataSet = '[ ' + s + ' ]'; 
     $('#example').DataTable({ 
      data: dataSet 
     }); 
    } 
} 

我希望它是這樣的格式

var dataSet = [ 
    ["m", "System Architect", "Edinburgh", "5421", "2011/04/25", "$320,800"], 
    ["Ashton Cox", "Junior Technical Author", "San Francisco", "1562", "2009/01/12", "$86,000"], 
    ["Cedric Kelly", "Senior Javascript Developer", "Edinburgh", "6224", "2012/03/29", "$433,060"], 
    ["Airi Satou", "Accountant", "Tokyo", "5407", "2008/11/28", "$162,700"] 
]; 
+0

餘噸如果你向我們展示你擁有的數據以及你想要的東西,那麼它會容易得多。如果您控制服務器,直接輸出正確的格式可能會更容易。 – adeneo

+0

你想要的格式是一個數組數組。你應該從這個角度來看待它,而不是一個括號括起來的字符串。 –

回答

0

使用下面的代碼來代替:

function getMsgHandler(responseTxt, statusTxt, xhr) { 
    if (statusTxt === "success") { 
     $('#example').DataTable({ 
      data: responseTxt, 
      columns: [ 
       { data: 'productID' }, 
       { data: 'name' }, 
       { data: 'description' }, 
       { data: 'img' }, 
       { data: 'price' } 
      ] 
     }); 
    } 
} 
+0

它沒有與我一起工作! –

+0

@AyaRadwan,請發佈'responseTxt'的內容。 –