我正在开发一个使用XMLHttpRequest的Chrome扩展程序,以便使用API。这是我到目前为止的代码:
myscript.js:
function httpGetAsync(theUrl) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
var bitcoinInfo = JSON.parse(xmlHttp.responseText);
output.innerHTML += bitcoinInfo.bpi.USD.rate;
tabTitle.innerHTML += bitcoinInfo.bpi.USD.rate;
}
xmlHttp.open("GET", theUrl, true);
xmlHttp.send(null);
};
var output = document.getElementsByClassName('bit-price')[0];
var tabTitle = document.querySelector('title');
document.addEventListener('DOMContentLoaded', httpGetAsync('http://api.coindesk.com/v1/bpi/currentprice.json'));
问题: 代码工作,它显示价格,但我不明白为什么我在检查器控制台中得到以下3个错误,如何改进我的代码,以阻止它们在控制台中显示:
Uncaught TypeError: Cannot read property 'bpi' of undefined
at XMLHttpRequest.xmlHttp.onreadystatechange (myscript.js:6)
at httpGetAsync (myscript.js:9)
at myscript.js:14
Uncaught TypeError: Cannot read property 'bpi' of undefined
at XMLHttpRequest.xmlHttp.onreadystatechange (myscript.js:6)
Uncaught TypeError: Cannot read property 'bpi' of undefined
at XMLHttpRequest.xmlHttp.onreadystatechange (myscript.js:6)
我尝试了什么: 我搜索了SO和谷歌,但遗憾的是没有找到任何可以帮我解决这个问题的东西。
答案 0 :(得分:0)
if
声明
function httpGetAsync(theUrl) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
var bitcoinInfo = JSON.parse(xmlHttp.responseText);
output.innerHTML += bitcoinInfo.bpi.USD.rate;
tabTitle.innerHTML += bitcoinInfo.bpi.USD.rate;
}
}
xmlHttp.open("GET", theUrl, true);
xmlHttp.send(null);
};
答案 1 :(得分:0)
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
var bitcoinInfo = JSON.parse(xmlHttp.responseText);
output.innerHTML += bitcoinInfo.bpi.USD.rate;
tabTitle.innerHTML += bitcoinInfo.bpi.USD.rate;
作为
if (xmlHttp.readyState == 4 && xmlHttp.status == 200){
var bitcoinInfo = JSON.parse(xmlHttp.responseText);
output.innerHTML += bitcoinInfo.bpi.USD.rate;
tabTitle.innerHTML += bitcoinInfo.bpi.USD.rate;
}
因为,对于前3个状态更改,var bitcoinInfo = JSON.parse(xmlHttp.responseText);
这不会起作用。因此,依赖于上述行的其余行会产生错误