2016-02-27 34 views
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); 

} 
+0

你說得對範圍。 'displayWeather'在全局範圍內不可用,只存在於'findWeather'函數範圍中。 – jsxqf

+0

很感謝。你可以添加這個答案嗎?謝謝。 – freeradik

回答

0

displayWeather是不是在全球範圍內可用的,只存在於findWeather功能範圍。

相關問題