JavaScript从WebApi加载交易数据至区块链浏览器表格失败排查
交易页面表格为空的排查与修复方案
1. 修复URL参数提取逻辑
你当前用window.location.search.substring(6)提取txId,这种写法依赖参数固定为?txid=开头,一旦参数大小写变化、位置变动就会提取错误。改用标准的URLSearchParams更可靠:
const urlParams = new URLSearchParams(window.location.search); const txId = urlParams.get('txid'); const target = '/blockchain/api/transactions/' + txId;
2. 添加错误捕获机制
现有代码只处理请求成功的情况,一旦API请求失败(网络问题、txId无效),无法定位问题。给请求添加catch块:
myagent.get(target) .then(res => { console.log(res.body); // 原有填充表格逻辑 document.getElementById('txId').innerHTML = res.body.txId; document.getElementById('txId').href = transactionsHref + res.body.txId; // ...其余赋值代码 }) .catch(err => { console.error('加载交易数据失败:', err); });
3. 校验API返回字段匹配性
打开浏览器控制台(F12)查看console.log(res.body)的输出,确认后端返回的字段名和前端使用的完全一致:
- 检查
txId、blockId、sender等字段的大小写、拼写是否和前端代码对应,比如后端如果返回txid(全小写),前端res.body.txId就会取不到值。
4. 确保DOM加载完成后执行脚本
将数据加载逻辑包裹在DOMContentLoaded事件中,避免极端情况下DOM未渲染完成就执行脚本导致元素获取失败:
document.addEventListener('DOMContentLoaded', function() { // 这里放原有的数据加载代码 const urlParams = new URLSearchParams(window.location.search); const txId = urlParams.get('txid'); const target = '/blockchain/api/transactions/' + txId; const transactionsHref = "transactions.html?txid="; const blocksHref = "blocks.html?blockid="; const accountsHref = "accounts.html?account="; const myagent = superagent.agent(); myagent.get(target) .then(res => { console.log(res.body); // 填充表格的代码 document.getElementById('txId').innerHTML = res.body.txId; document.getElementById('txId').href = transactionsHref + res.body.txId; document.getElementById('blockId').innerHTML = res.body.blockId; document.getElementById('blockId').href = blocksHref + res.body.blockId; document.getElementById('sender').innerHTML = res.body.sender; document.getElementById('sender').href = accountsHref + res.body.sender; document.getElementById('receiver').innerHTML = res.body.receiver; document.getElementById('receiver').href = accountsHref + res.body.receiver; document.getElementById('amount').innerHTML = res.body.amount; document.getElementById('nonce').innerHTML = res.body.nonce; document.getElementById('transactionFeeLimit').innerHTML = res.body.transactionFeeLimit; document.getElementById('transactionFee').innerHTML = res.body.transactionFee; document.getElementById('transactionFeeBasePrice').innerHTML = res.body.transactionFeeBasePrice; }) .catch(err => { console.error('加载失败:', err); }); });
内容的提问来源于stack exchange,提问作者Thriest
相关产品推荐
相关产品推荐

