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

时间:2023-01-15 03:45:01

This is the link to my codepen: http://codepen.io/dsemel/pen/VamEyE

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

This is the section of code that seems to be the problem:

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

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 个解决方案

#1


0  

I think your code works fine you just missed a small thing in your code i corrected that http://codepen.io/rahulchaturvedie/pen/RagGdR

我认为你的代码工作正常你只是错过了你的代码中的一个小东西我纠正了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);  
   }   
  });

#2


1  

Make sure you check your developer tools console when you encounter these errors. Your code is throwing this error Uncaught TypeError: Cannot read property '0' of undefined.

遇到这些错误时,请务必检查开发人员工具控制台。您的代码抛出此错误Uncaught TypeError:无法读取未定义的属性“0”。

The condition object is part of the current object, therefore you have to access the current object before accessing the condition object.

条件对象是当前对象的一部分,因此您必须在访问条件对象之前访问当前对象。

Updated working codepen

更新了工作代码

#1


0  

I think your code works fine you just missed a small thing in your code i corrected that http://codepen.io/rahulchaturvedie/pen/RagGdR

我认为你的代码工作正常你只是错过了你的代码中的一个小东西我纠正了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);  
   }   
  });

#2


1  

Make sure you check your developer tools console when you encounter these errors. Your code is throwing this error Uncaught TypeError: Cannot read property '0' of undefined.

遇到这些错误时,请务必检查开发人员工具控制台。您的代码抛出此错误Uncaught TypeError:无法读取未定义的属性“0”。

The condition object is part of the current object, therefore you have to access the current object before accessing the condition object.

条件对象是当前对象的一部分,因此您必须在访问条件对象之前访问当前对象。

Updated working codepen

更新了工作代码