ajax没有加载/检索数据

时间:2015-09-02 13:07:33

标签: javascript ajax

我正在进行FreeCodeCamp课程,并且我正在尝试构建一个天气应用程序。我找到了一个关于如何通过地理位置获得纬度和经度的精彩教程。但是现在当我尝试运行应用程序时,它似乎无法检索ajax数据供我解析。我在本地尝试并将其移动到主机思考可能是它但现在我只是在我的HTML的第一行得到一个奇怪的错误,我没有看到任何错误。谢谢你这里是代码,它在weatherapp.boomersplayground.com上直播

的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);
});

2 个答案:

答案 0 :(得分:0)

因为您将异步调用视为同步调用。 Ajax调用需要在getCurrentPosition的成功回调中。在返回at和lng之前,您正在构建Ajax URL。

答案 1 :(得分: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);
    }
});