在JavaScript中,将数据从一个页面传递到另一个页面并在表格中显示,可以通过多种方式实现。以下是一些常见的方法及其基础概念、优势、类型、应用场景以及示例代码。
// 页面A:传递数据
const data = { name: 'Alice', age: 25 };
const queryString = Object.keys(data).map(key => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`).join('&');
window.location.href = `pageB.html?${queryString}`;
// 页面B:接收数据并显示在表格中
window.onload = function() {
const urlParams = new URLSearchParams(window.location.search);
const name = urlParams.get('name');
const age = urlParams.get('age');
const table = document.createElement('table');
const row = table.insertRow();
const cell1 = row.insertCell(0);
const cell2 = row.insertCell(1);
cell1.textContent = 'Name';
cell2.textContent = name;
const row2 = table.insertRow();
const cell3 = row2.insertCell(0);
const cell4 = row2.insertCell(1);
cell3.textContent = 'Age';
cell4.textContent = age;
document.body.appendChild(table);
};
// 页面A:传递数据
const data = { name: 'Alice', age: 25 };
localStorage.setItem('userData', JSON.stringify(data));
window.location.href = 'pageB.html';
// 页面B:接收数据并显示在表格中
window.onload = function() {
const data = JSON.parse(localStorage.getItem('userData'));
const table = document.createElement('table');
const row = table.insertRow();
const cell1 = row.insertCell(0);
const cell2 = row.insertCell(1);
cell1.textContent = 'Name';
cell2.textContent = data.name;
const row2 = table.insertRow();
const cell3 = row2.insertCell(0);
const cell4 = row2.insertCell(1);
cell3.textContent = 'Age';
cell4.textContent = data.age;
document.body.appendChild(table);
};
JSON.stringify
和JSON.parse
确保数据格式正确,并在接收端进行验证。通过以上方法和注意事项,可以有效地在不同页面间传递数据并在表格中显示。
领取专属 10元无门槛券
手把手带您无忧上云