首页 > 解决方案 > 在不刷新页面的情况下更新页面内容 cURL 和 ajax

问题描述

我有一个发送 ajax 请求的表单,它从 cURL 请求返​​回一个 json 对象。我使用表单使用开始日期和结束日期查询 API。我已经设法显示返回到表中的数据。现在我的问题是每次从我的表单发出新请求时,在我通过上一个请求获得的表格之后,表格页面就会显示一个新表格,有没有办法只显示一个表格,所以在每个表格请求用新数据替换以前的数据?

这是我的 JavaScript 代码

**$(document).ready(function() {
  // Function to create table layout
  function createTable(data) {
    var table = document.createElement('table');
    var header = table.insertRow();
    for(var h in data[0]) {
      var th = document.createElement('th');
      th.innerHTML = h;
      header.appendChild(th);
    }
    table.classList.add('table','table-bordered');
    data.forEach(function(item) {
      var row = table.insertRow();
      for(var v in item) {
        var cell = row.insertCell();
        if (Array.isArray(item[v])) {
          var subtable = createTable(item[v]);
          cell.appendChild(subtable);
        }
        else {
          cell.innerHTML = item[v];
        }
      }
    })
    return table;
  }
  // Initialize air datepicker plugin
  $('.air-datepicker').datepicker();
  // Store form into variable
  var form= $("#requestForm");
  // Actions when form is submitted
  $('#submitForm').click(function(e) {
    // Ajax request
    $.ajax({
      type: "POST",
      url: form.attr("action"),
      data: form.serialize(),

      success: function(result){
        // Show the table container
        $('#tableContainer').css('display','block');
        // Convert reponse into JSON
        datas = JSON.parse(result);
        // Get nome condominio and show it
        $('#nome_condominio').html(datas.condomini[0].condominio.nome);
        // Get indirizzo condomino and show it
        $('#indirizzo_condominio').html(datas.condomini[0].condominio.indirizzo);
        // Put datas into table using the function createTable
        var table = createTable(datas.condomini[0].ricevute);
        // Show table 
        $('#table').append(table);
        console.log(result);
      },
      error: function(error, status, xhr) {
        console.log(error, status, xhr);

      }
    }); // Fine ajax

   e.preventDefault(); // Prevent form to be sent
  }); // fine submit form

}); // fine document ready**

标签: javascriptajaxcurl

解决方案


// Show table
$('#table').html(table);

您替换 DOM 节点的 html 内容,#table而不是将新表附加到现有内容(包括先前生成的表)。

现在,如果#table在通话时应该是空的,那么该解决方案就可以了。

否则,如果存在任何内容(例如表头),它会被删除,您必须找到重建它的方法。


推荐阅读