【发布时间】:2018-06-18 18:08:51
【问题描述】:
简介
您好,我在使用 JSON 提取 API 数据时遇到问题,但在显示或处理数据时遇到问题。
我的代码
function pullingInformation () {
var data = new XMLHttpRequest();
data.open('GET', 'RANDOM URL CANT SHOW API KEY');
data.onload = function () {
if (data.status >= 200 && data.status < 400) {
// Different types of JSON.random(). Examples are: parse() and stringify();
var ourData = JSON.stringify(data.responseText);
var tempOurData = JSON.parse(ourData);
tempHTML = WeatherHTML(tempOurData);
$('#DivID').html(tempHTML);
}
else {
$('#DivID').html('Server failure, please try again!');
}
};
data.onerror = function () {
$('#DivID').html('Connection error ocurred, please try again!');
}
}
function WeatherHTML (data) {
tempHTML = data;
console.log(tempHTML);
console.log(tempHTML.coord);
return tempHTML.coord;
}
问题
当我console.log() tempHTML 时,我从 API 中获取了整个代码,但如果我尝试只获取如下所示的特定代码位:
{"coord":{"lon":45.1,"lat":12.45},"weather":[{"id":801,"main":"Clouds","description":"few clouds","icon":"02n"}],"base":"stations","main:{"temp":298.508,"pressure":1031.37,"humidity":97,"temp_min":298.508,"temp_max":298.508,"sea_level":1031.75,"grnd_level":1031.37},"wind":{"speed":5.72,"deg":92.5012},"clouds":{"all":12},"dt":1515515421,"sys":{"message":0.0155,"country":"YE","sunrise":1515468218,"sunset":1515509418},"id":6940814,"name":"Craiter","cod":200}
例如 tempHTML.coord 返回我“未定义”。我做错了什么,我的错误在哪里?我只是将信息拉错还是以不正确的方法调用对象?
【问题讨论】:
-
"tempHTML.coord" — 您不会在主代码示例中的任何地方使用它。您应该提供一个真实的minimal reproducible example,它没有碎片化。
-
你应该enable Strict mode。隐式全局变量是编写难以维护的代码的好方法。
-
我不明白你的意思?另外,我的错误在哪里,我将编辑问题!
标签: javascript json api object