Javascript 显示来自ajax json解析的数据时出现问题
这是指向我的代码笔的链接: 这是代码中似乎存在问题的部分:Javascript 显示来自ajax json解析的数据时出现问题,javascript,jquery,json,ajax,Javascript,Jquery,Json,Ajax,这是指向我的代码笔的链接: 这是代码中似乎存在问题的部分: function success(position){ var WeatherKey = '6068dffce2f44535a07202457162103'; var lat = position.coords.latitude; var long = position.coords.longitude; var weatherUrl = "http://api.apixu.com/v1/current.json?
function success(position){
var WeatherKey = '6068dffce2f44535a07202457162103';
var lat = position.coords.latitude;
var long = position.coords.longitude;
var weatherUrl = "http://api.apixu.com/v1/current.json?key=" + WeatherKey +
"&q=" + lat + "," + long;
$.ajax({
url : weatherUrl,
type: 'GET',
dataType : 'json',
success : function(data) {
var city = data['location']['name'];
var tempFar = data['current']['temp_f'];
var img = data['condition'][0]['icon'];
var desc = data['condition']['text'];
$('#weatherInfo2').text(tempFar);
}
});
}
当遇到这些错误时,请确保检查开发人员工具控制台。您的代码抛出此错误
未捕获类型错误:无法读取未定义的属性“0”
条件
对象是当前
对象的一部分,因此您必须在访问条件
对象之前访问当前
对象
我认为你的代码运行得很好。你只是在代码中漏掉了一点小东西。我纠正了这一点
tempFar数据将不会显示在页面上。我很高兴能提供帮助。
$.ajax({
url : weatherUrl,
type: 'GET',
dataType : 'json',
success : function(data) {
console.log(data);
var city = data['location']['name'];
var tempFar = data['current']['temp_f'];
var img = data.current.condition.icon; // correct this
var desc = data.current.condition.text; // correct this
$('#weatherInfo2').text(tempFar);
}
});