0
我正在处理简单的跨域JSONP API调用。在第一个代码中,函数findWeather中定义了回调函数displayWeather。这给了“Uncaught ReferenceError ..... displayWeather is not defined”错误。第二个代码有效。我无法弄清楚为什么第一个案件不起作用。任何解释将不胜感激。谢谢。 编辑:我想知道这是否与范围界定有关?和/或与API调用结合起来?为什么在api调用中定义一个函数内部的回调函数会抛出一个“Uncaught ReferenceError”?
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'函数范围中。 – jsxqf
很感谢。你可以添加这个答案吗?谢谢。 – freeradik