2015-10-18 97 views
0

我有jQuery中下面的代碼:如何將json數據轉換爲jQuery中的html表格?

    $.ajax({ 
         url: './getJson.php', 
         type: "POST", 
         data: { 
          email: email 
         }, 
         dataType:'text', 
         success: function(response) 
         { 
          alert(response) 
         } 
        }); 

,並在我的網頁運行它後,我看到一個彈出我的JSON數據,它具有結構:

[{"number":"1","id":"2","price":"100.70","date":"2015-10-18 03:00:00"}, 
{"number":"2","id":"2","price":"88.20","date":"2015-10-18 04:00:00"}] 

當發生這種情況的用戶進入我的頁面。相反,我想填補一個HTML表格與數據,並已準備佈局(目前爲止以虛擬數據填充):

     <div class="panel-body"> 
          <div class="dataTable_wrapper"> 
           <table class="table table-striped table-bordered table-hover" id="dataTables-example"> 
            <thead> 
             <tr> 
              <th>number</th> 
              <th>id</th> 
              <th>price</th> 
              <th>date</th> 
             </tr> 
            </thead> 
            <tbody> 
             <tr class="odd gradeX"> 
              <td>Trident</td> 
              <td>Internet Explorer 4.0</td> 
              <td>Win 95+</td> 
              <td class="center">4</td> 
             </tr> 
             <tr class="even gradeC"> 
              <td>Trident</td> 
              <td>Internet Explorer 5.0</td> 
              <td>Win 95+</td> 
              <td class="center">5</td> 
             </tr> 
             <tr class="odd gradeA"> 
              <td>Trident</td> 
              <td>Internet Explorer 5.5</td> 
              <td>Win 95+</td> 
              <td class="center">5.5</td> 
             </tr> 

現在的問題是 - 我怎麼可以用我自己的替代將假數據,從json中獲取並始終顯示爲用戶的好桌子? 謝謝!

回答

3
  1. 解析使用$.parseJSON(或JSON.parse)使用$.each()
  2. JSON字符串或一組dataType : 'json'
  3. 遍歷所解析的對象生成tr與內容並將其附加到該表使用appendTo()append()

var data = '[{"number":"1","id":"2","price":"100.70","date":"2015-10-18 03:00:00"},{"number":"2","id":"2","price":"88.20","date":"2015-10-18 04:00:00"}]'; 
 

 
json = JSON.parse(data); 
 

 
$.each(json, function(i, v) { 
 
    $('<tr/>', { 
 
    html: [$('<td/>', { 
 
     text: v.number 
 
    }), $('<td/>', { 
 
     text: v.id 
 
    }), $('<td/>', { 
 
     text: v.price 
 
    }), $('<td/>', { 
 
     text: v.date 
 
    })] 
 
    }).appendTo('#dataTables-example tbody') 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div class="panel-body"> 
 
    <div class="dataTable_wrapper"> 
 
    <table class="table table-striped table-bordered table-hover" id="dataTables-example"> 
 
     <thead> 
 
     <tr> 
 
      <th>number</th> 
 
      <th>id</th> 
 
      <th>price</th> 
 
      <th>date</th> 
 
     </tr> 
 
     </thead> 
 
     <tbody> 
 
     </tbody> 
 
    </table>