【问题标题】:jQuery.Deferred exception: Cannot read property '0' of undefined" "TypeError: Cannot read property '0' of undefinedjQuery.Deferred 异常:无法读取未定义的属性 '0'" "TypeError:无法读取未定义的属性 '0'
【发布时间】:2017-11-06 03:07:51
【问题描述】:

我继续使用codepen:jQuery.Deferred exception: Cannot read property '0' of undefined" "TypeError: Cannot read property '0' of undefined 在控制台上收到此消息。

我的 javascript 代码:

var api_key = "fa15d403d0ab55e3cfd6e0867bbb0114";
$(document).ready(function(){
  var loc;
  //Call the location   
$.getJSON('https://ipinfo.io', function(data){
  loc = data.loc.split(",");
  console.log(loc);
 });
  $.getJSON('http://api.openweathermap.org/data/2.5/weather?lat=' + loc[0]  +  '&lon=' + loc[1] + '&APPID='+ api_key, function(weather){
         console.table("c ,",weather);
          });
});

【问题讨论】:

  • console.log(loc);时你在控制台看到了什么
  • '''loc' 表示位置,所以它控制台记录纬度和经度。

标签: jquery api


【解决方案1】:

这意味着您正在尝试读取 undefined 对象的 0 属性。

根据您共享的代码,这里发生了这种情况:loc[0] - loc 未定义,因此会引发错误。

它未定义的原因是因为异步排序 - 您的第一个函数尚未在它设置 loc 的位置执行回调。尝试将第二个调用放入第一个函数(就在您的console.log 调用之后)而不是在它之后。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-26
    • 2019-11-20
    • 1970-01-01
    相关资源
    最近更新 更多