javascript - 在不刷新页面的情况下更新页面内容 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**
解决方案
和
// Show table
$('#table').html(table);
您替换 DOM 节点的 html 内容,#table
而不是将新表附加到现有内容(包括先前生成的表)。
现在,如果#table
在通话时应该是空的,那么该解决方案就可以了。
否则,如果存在任何内容(例如表头),它会被删除,您必须找到重建它的方法。
推荐阅读
- javascript - 我如何在 JS 中设置会话以进行输入?
- javascript - Google Maps JavaScript API v3 无法正常工作
- html - CSS 3 伪元素
- php - 从 Laravel 5.7 升级到 5.8 会返回错误:Class Blade.compiler 不存在.... post-autoload-dump 事件返回错误代码 1
- pdf - Flutter 打印包:使用循环创建 pdf 表
- excel - 如何从每周更改名称的工作簿中提取信息?
- git - git 服务器必须安装 git 吗?
- rest - 在设计 Restful API 时,我应该使用 DELETE 还是 POST 来取消关注?
- c# - 如何在 XAML 中重复编程行?
- tensorflow - 设置初始随机种子时选择正确的超参数