Javascript 将JSON数据追加到HTML表的问题

Javascript 将JSON数据追加到HTML表的问题,javascript,php,html,json,Javascript,Php,Html,Json,在将json数据显示到html表后,我遇到了问题 问题 每次我更改产品id时,表值总是添加新数据 如果结果为空,则tbody表仍显示当前以前的数据 这是我的密码: <table class="table" id="history_maintenance"> <thead> <th>Date In</th> <th>SPK No</th> <th>

在将json数据显示到html表后,我遇到了问题

问题

  • 每次我更改产品id时,表值总是添加新数据
  • 如果结果为空,则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>
    
    
    约会
    SPK号
    购买编号
    维护说明
    $('#product_id')。在('change',function()上{
    让customer\u name=document.getElementById(“customer\u name”).value;
    让phone=document.getElementById(“phone”).value;
    让car\u plate\u no=document.getElementById(“car\u plate\u no”).value;
    让car_type=document.getElementById(“car_type”).value;
    让product_id=document.getElementById(“product_id”).value;
    $.ajax({
    类型:“POST”,
    url:“”,
    数据类型:“json”,
    cache:false,
    数据:{
    客户名称:客户名称,
    电话:电话,,
    车牌号:车牌号,
    车型:车型,
    产品标识:产品标识,
    },
    成功:函数(数据历史记录){
    让transactionHistory='';
    对于(i=0;i
    谢谢@EL_vanja的提示

    我补充说:

    $('#history_maintenance tbody').html('');
    
    之前:

    let transactionHistory = '';
    

    这就是追加的意思——添加到已有的内容中。您似乎只需要覆盖文本内容。如何覆盖文本内容?我的意思是,我可以学习什么函数或文章来解决这个问题?这只是一个简单的赋值:
    yourElement.textContent=yourValue
    。或者,如果你想坚持使用jQuery函数,那就是。