【问题标题】:Why does defining a callback function inside a function with the api call throw an "Uncaught ReferenceError"?为什么使用 api 调用在函数内部定义回调函数会引发“未捕获的 ReferenceError”?
【发布时间】:2016-02-27 07:41:25
【问题描述】:

我正在处理一个简单的跨域 JSONP API 调用。在第一个代码中,回调函数 displayWeather 定义在函数 findWeather 内。这给出了 "Uncaught ReferenceError ..... displayWeather is not defined" 错误。第二个代码有效。我无法弄清楚为什么第一个案例不起作用。任何解释将不胜感激。谢谢。 编辑:我想知道这是否与范围界定有关?和/或范围与 api 调用相结合?

  function findWeather(lat, lon) {

  var weatherApi = document.createElement("script");

  function displayWeather(weather) {
    document.getElementById("cityCountry").innerHTML = "City: "+weather.name;
  }

  weatherApi.type = "text/javascript";
  weatherApi.src = "http://api.openweathermap.org/data/2.5/weather?lat="+lat+"&lon="+lon+"&appid=137bbb43f4df58953838eefe6b9c3044&callback=displayWeather";
  document.head.appendChild(weatherApi);

}

下面的第二个代码有效

function displayWeather(weather) {
    document.getElementById("cityCountry").innerHTML = "City: "+weather.name;
  }

function findWeather(lat, lon) {

  var weatherApi = document.createElement("script");

  weatherApi.type = "text/javascript";
  weatherApi.src = "http://api.openweathermap.org/data/2.5/weather?lat="+lat+"&lon="+lon+"&appid=137bbb43f4df58953838eefe6b9c3044&callback=displayWeather";
  document.head.appendChild(weatherApi);

}

【问题讨论】:

  • 您对范围的看法是正确的。 displayWeather在全局范围内不可用,只存在于findWeather函数范围内。
  • 非常感谢。您可以将此添加为答案吗?谢谢。

标签: javascript api scope callback


【解决方案1】:

displayWeather在全局范围内不可用,只存在于findWeather函数范围内。

【讨论】:

    猜你喜欢
    • 2017-01-17
    • 2012-02-01
    • 2013-06-27
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多