无法显示来自ajax json解析的数据

时间:2016-03-26 00:31:52

标签: javascript jquery json ajax

这是我的codepen的链接:http://codepen.io/dsemel/pen/VamEyE

这是似乎是问题的代码部分:

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);  
}

 });
}

2 个答案:

答案 0 :(得分:1)

确保在遇到这些错误时检查开发人员工具控制台。您的代码抛出此错误Uncaught TypeError: Cannot read property '0' of undefined

condition对象是current对象的一部分,因此您必须在访问current对象之前访问condition对象。

Updated working codepen

答案 1 :(得分:0)

我认为你的代码工作正常,你错过了代码中的一小部分我纠正了这一点 http://codepen.io/rahulchaturvedie/pen/RagGdR

$.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);  
   }   
  });