簡體   English   中英

Append JSON 數據到 HTML 表的問題

[英]Append Problem with JSON data to HTML Table

將 json 數據顯示到 html 表后出現問題。

問題;

  1. 每次我更改 product_id 時,表值總是添加新數據。
  2. 如果結果是 null,tbody 表仍然顯示當前之前的數據。

這是我的代碼:

<table class="table" id="history_maintenance">
  <thead>
    <th>Date In</th>
    <th>SPK No</th>
    <th>Purchase No</th>
    <th>Maintenance Notes</th>
  </thead>
  <tbody></tbody>
</table>

<script>
$('#product_id').on('change', function() {

let customer_name = document.getElementById("customer_name").value;
let phone = document.getElementById("phone").value;
let car_plate_no = document.getElementById("car_plate_no").value;
let car_type = document.getElementById("car_type").value;
let product_id = document.getElementById("product_id").value;

$.ajax({
    type: "POST",
    url: "<?php echo base_url('spk/get_customer_transaction_history') ?>",
    dataType: "json",
    cache: false,
    data: {
        customer_name: customer_name,
        phone: phone,
        car_plate_no: car_plate_no,
        car_type: car_type,
        product_id: product_id,
    },

    success: function(dataHistory) {
      let transactionHistory = '';

      for (i = 0; i < dataHistory.length; i++) {
        transactionHistory += '<tr>';
        transactionHistory += '<td>' + dataHistory[i].date_in + '</td>';
        transactionHistory += '<td>' + dataHistory[i].spk_no + '</td>';
        transactionHistory += '<td>' + dataHistory[i].purchase_no + '</td>';
        transactionHistory += '<td>' + dataHistory[i].spk_maintenance_notes + '</td>';
        transactionHistory += '</tr>';
      }

      $('#history_maintenance tbody').append(transactionHistory);
    }
   });
   return false;
});
</script>

感謝@EL_vanja 的提示

我補充說:

$('#history_maintenance tbody').html('');

前:

let transactionHistory = '';

暫無
暫無

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

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