2015-09-02 41 views
0

我正在做FreeCodeCamp課程,我正在嘗試構建一個天氣應用程序。我找到了一個關於如何通過地理定位獲取經緯度的好教程。但是現在,當我嘗試運行應用程序時,它似乎沒有檢索到我需要解析的ajax數據。我在本地嘗試,並將其轉移到託管思維,可能是它,但現在我只是在我的一個網頁上得到一個奇怪的錯誤,我沒有看到任何錯誤。在這裏感謝傢伙的代碼,它是現場直播weatherapp.boomersplayground.comajax不加載/檢索數據

的index.html

<!doctype html> 
<html> 
<head> 
<meta charset="utf-8"> 
<title>Weather APP</title> 
<link rel="stylesheet" href="style.css"> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
<script src='script.js'></script> 
</head> 
<body> 
<div id="forecast"> 
<h1>Weather at <span id="location"> </span></h1> 
<!-- <div id="imgdiv"> 
<img id="img" src=""/> --> 
</div> 
<p>It is currently <span id="temp"> </span>F with <span id="desc"> </span></p> 
<p>Wind: <span id="wind"></span></p> 
</div> 
</body> 
</html> 

的script.js

$(document).ready(function(){ 
    var Geo = {}; 
    if (navigator.geolocation){ 
    navigator.geolocation.getCurrentPosition(success,error); 
    } else { 
    alert('Geolocation is not supported'); 
    } 

    function error(){ 
    alert("That's weird! We couldn't find you!"); 
    } 

    function success(position){ 
    Geo.lat = position.coords.latitude; 
    Geo.lng = position.coords.longitude; 
    } 

    var key = 'c7e3b3ac66e765aa'; 
    var Weather = "http://api.wunderground.com/api/"+ key +"/geolookup/conditions/q/" + Geo.lat + "," + Geo.lng + ".json"; 

    $.ajax({ 
    url : Weather, 
    dataType : 'jsonp', 
    success : function(data) { 
     var location =data['location']['city']; 
     var temp = data['current_observation']['temp_f']; 
     var img = data['current_observation']['icon_url']; 
     var desc = data['current_observation']['weather']; 
     var wind = data['current_observation']['wind_string']; 
     } 
    }) 


    //setting the spans to the correct parameters 
$('#location').html(location); 
$('#temp').html(temp); 
$('#desc').html(desc); 
$('#wind').html(wind); 
// filling the image src attribute with the image url 
// $('#img').attr('src', img); 
}); 

回答

0

您可以使用在success回調之外的AJAX響應初始化的變量。您應該在回調中使用它們,因爲它們是異步創建的:

$.ajax({ 
    url : Weather, 
    dataType : 'jsonp', 
    success : function(data) { 
     var location =data['location']['city']; 
     var temp = data['current_observation']['temp_f']; 
     var img = data['current_observation']['icon_url']; 
     var desc = data['current_observation']['weather']; 
     var wind = data['current_observation']['wind_string']; 
     $('#location').html(location); 
     $('#temp').html(temp); 
     $('#desc').html(desc); 
     $('#wind').html(wind); 
    } 
}); 
+0

AHHHHHHH。這現在更有意義!非常感激!!! – boomer1204

+0

這絕對有助於我寫入html,但我的ajax調用仍然沒有檢索頁面供我解析? – boomer1204

+0

您收到哪個AJAX響應? – LostMyGlasses

0

因爲你是治療的異步調用作爲一個同步。 Ajax調用需要位於getCurrentPosition的成功回調中。您在返回at和lng之前正在構建Ajax url。