2017-05-11 12 views
1

天気の詳細をこのAPIから取得したいのですが、何らかの奇妙な理由で動作しないようです。天気json APIを使用できません

これはmashape APIです。 https://market.mashape.com/fyhao/weather-13

はここで任意の助けが理解されるであろう

function getWeather() { 
    var lat=null; 
    var lon=null; 
    if (navigator.geolocation) { 
    navigator.geolocation.getCurrentPosition(function(position) { 
     lat = position.coords.latitude; 
     lon = position.coords.longitude; 
    }); 
    } 
    var url = 
    "http://simple-weather.p.mashape.com/weatherdata?lat=" + 
    lat + 
    "&lng=" + 
    lon; 
    $.ajax({ 
    url: url, 
    type: "GET", 
    dataType: "json", 
    success: function(data) { 
     $(".location").html(
     "<h4>" + 
      data.query.results.channel.location.city + 
      ", " + 
      data.query.results.channel.location.country + 
      "</h4>" 
    ); 
     $(".weather").html(
     "<h4>" + data.query.results.channel.item.condition.text + "</h4>" 
    ); 
     $(".temperature").html(
     "<h4>" + data.query.results.channel.item.condition.temp + "</h4>" 
    ); 
    }, 
    error: function(err) { 
     alert(err); 
    }, 
    beforeSend: function(xhr) { 
     xhr.setRequestHeader(
     "X-Mashape-Authorization", 
     "MYKEY" 
    ); 
    } 
    }); 
} 
$(document).ready(function() { 
    $(".info").addClass("animated pulse"); 
    getWeather(); 
}); 

、私が試したものです。

編集: - 私は、「[オブジェクトのオブジェクト]」により、AJAXでの誤差関数に言う警告エラーを取得しています。ページのポップアップをブロックしたため、最初はエラーが表示されませんでした。物事の

+0

はあなたが取得しているか、エラーを指定してくださいできますか? –

+0

@MannanBahelim私は何も得ていません。 –

+0

私はそれがHTTPレスポンスを返し、あなたはあなたが 'getWeatherを呼び出していることを確認している場合は、多分、「何を取得しない」についてどのようにRUは必ず答え –

答えて

4

カップル:

  • getCurrentPosition()が非同期です。 latとlon変数が座標に設定されるまでに、$ .ajaxリクエストはすでにnullのlat変数とlon変数で送信されています
  • このAPIはHTTPを要求していません。
  • ヘッダはここX-Mashape-Authorization

X-Mashape-Keyとない場合の例である:

function getWeather() { 
    var lat = null; 
    var lon = null; 
    if (navigator.geolocation) { 
     //we are putting everything inside the callback 
     navigator.geolocation.getCurrentPosition(function (position) { 
      lat = position.coords.latitude; 
      lon = position.coords.longitude; 

      var url = 
       "https://simple-weather.p.mashape.com/weatherdata?lat=" + 
       lat + 
       "&lng=" + 
       lon; 
      $.ajax({ 
       url: url, 
       type: "GET", 
       success: function (data) { 
        console.log(data); 
       }, 
       error: function (err) { 
        console.error('error ' + JSON.stringify(err)); 
       }, 
       beforeSend: function (xhr) { 
        xhr.setRequestHeader(
         "X-Mashape-Key", "KEY" 
        ); 
       } 
      }); 

     }); 
    } 
} 
$(document).ready(function() { 

    getWeather(); 
}); 
+0

私の前のコメントを無視してください。いい答えだ! – Jamiec