javascript - JSON输入错误的意外结束,但似乎该方法已经运行?
问题描述
我正在使用 etherscan API 返回一些事件的日志。我想我正在以一种非常传统的方式解析 json,但它抛出了一个错误,说 JSON 意外结束
function getEventHistory() {
const topic0 = web3.utils.keccak256(config.event_string);
document.getElementById("topic0").innerHTML = topic0;
const qry = ("https://api.etherscan.io/api?module=logs&action=getLogs"+
"&fromBlock="+10338000+
"&toBlock="+"latest"+
"&address="+config.address+
"&topic0="+topic0+
"&apikey="+config.ether_api);
console.log(qry)
const request = new XMLHttpRequest()
request.open("GET", qry);
request.send();
request.onreadystatechange=(e)=>{
// document.getElementById("rLogsResp").innerHTML = request.responseText;
parseResponse(request.responseText);
}
}
function parseResponse(jsonString) {
console.log("Converting string to jsonString: "+jsonString);
const jsonObj = JSON.parse(jsonString)
console.log("Full Response: "+jsonObj);
var logs = []
for (var i = 0; i < jsonObj.result.length; i++) {
console.log("Element Number: "+i);
var event = jsonObj.result[i];
console.log("Index: "+event);
const parsedEvent = new Event(event);
logs.push(parsedEvent)
console.log(parsedEvent);
}
}
class Event {
constructor(event) {;
console.log("Parse address: "+event.address);
this.address = web3.utils.toAscii(event.address);
console.log("Parse topics: "+event.topics);
this.topics = [web3.utils.toAscii(event.topics[0]), web3.utils.toAscii(event.topics[1]), web3.utils.toAscii(event.topics[2])];
console.log("Parse data: "+event.data);
this.data = web3.utils.toAscii(event.data);
console.log("Parse blockNumber: "+event.blockNumber);
this.blockNumber = web3.utils.toAscii(event.blockNumber);
console.log("Parse timeStamp: "+event.timeStamp);
this.timeStamp = web3.utils.toAscii(event.timeStamp);
console.log("Pares gasPrice: "+event.gasPrice);
this.gasPrice = web3.utils.toAscii(event.gasPrice);
console.log("Parse gasUsed: "+event.gasUsed);
this.gasUsed = web3.utils.toAscii(event.gasUsed);
console.log("Parse logIndex: "+event.logIndex);
this.logIndex = web3.utils.toAscii(event.logIndex);
console.log("Parse transactionHash: "+event.transactionHash);
this.transactionHash = web3.utils.toAscii(event.transactionHash);
console.log("Parse transactionIndex: "+event.transactionIndex)
this.transactionIndex = web3.utils.toAscii(event.transactionIndex);
}
}
我对 JS 很陌生,但似乎onreadystatechange
被多次调用,因为错误出现在上面,const jsonObj = JSON.parse(jsonString)
但随后我从下面的 for 循环中获取日志。
关于什么是错的以及如何解决它的任何想法?
解决方案
你是对的。onreadystatechange
确实被多次调用。
文档描述了它们何时被调用,您可以使用该readyState
属性来找出 XHR 当前处于什么状态:
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/onreadystatechange
推荐阅读
- http - 来自 netcat 的 Web 响应中的最后一个数字
- python - 根据参考列表集分配熊猫列
- docker - 如何设置需要访问 s3 并将被推送到在 ECS 中运行的 ECR 的 dockerfile
- powershell - 向 Discord 发送增量数字的 PowerShell 脚本
- python - 调度私有类方法
- python - os.listdir 在 Colab 和 Jupyter 中的工作方式不同
- java - 类型参数中的 Bean Validation 注解是否有效?
- android - CTS 失败 dEQP-VK.api
- python - 在 Python 中通过三个列表的元素替换一个值
- php - 如何在条码下添加文字:php-barcode-generator