2016-12-04 16 views
-2

openweathermap.orgからJSONデータを取得しようとしていますが、$ .getJSONは機能しません。 ブラウザからAPIを呼び出すと、JSONデータが表示されますが、JSファイルでは機能しません。Weather APIを取得できません

$(document).ready(function(){ 
$("#button").click(function(){ 
    navigator.geolocation.getCurrentPosition(location,error,{timeout:10000});  
}); 
function location(pos){ 
    $("#crd").html("Location: " + pos.coords.latitude + " , " + pos.coords.longitude); 

    $.getJSON("api.openweathermap.org/data/2.5/weather?lat="+pos.coords.latitude+"&lon="+pos.coords.longitude+"&APPID=key", function(json){ 
     $("#weather").html(JSON.stringify(json)); 
    }); 

} 
function error(err){ 
    var errorCode = ""; 
    switch(err.code) { 
    case err.PERMISSION_DENIED: 
     errorCode = "User denied the request for Geolocation."; 
     break; 
    case err.POSITION_UNAVAILABLE: 
     errorCode = "Location information is unavailable."; 
     break; 
    case err.TIMEOUT: 
     errorCode = "The request to get user location timed out."; 
     break; 
    case err.UNKNOWN_ERROR: 
     errorCode = "An unknown error occurred."; 
     break;  
    } 
    $("#crd").html("Error " + err.code + ": " + errorCode); 
} 
}); 

もう1つ問題があります。 http://を追加するとlocalhostで動作しますが、codepenでは動作しません。何か案が?

私はcodepenにあなたがあなたがshemeを逃しているhttps://cors-anywhere.herokuapp.com/

+1

あなたがのためのアドレスを固定する必要がありますそれは別のドメインを適切に参照するためです。これを行うには、開始時(オプションでプロトコル)に '/ /'を追加することで可能です - '' //api.openweathermap.org/... "'。それ以外の場合、アドレスは現在のページとの相対的な扱いとなり、 'api.openweathermap.org'は有効なディレクトリ名となります。 –

+0

スキーム( 'http://'や 'https://'、あるいは現在のスキームを使うのに '//')を含む完全なURLを使用するとよいでしょう。 – jcaron

+1

あなたのお気に入りのブラウザのインス​​ペクタ/開発ツールでのリクエストは、おそらくかなり早く問題を強調していたでしょう。 – jcaron

答えて

1

ようないくつかのクロスの原点を使用する必要が解決策を見つけた:http://これを試してみてください。

$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat="+pos.coords.latitude+"&lon="+pos.coords.longitude+"&APPID=key", function(json){ 
    $("#weather").html(JSON.stringify(json)); 
}); 
+0

これは機能します。どうもありがとう。 – Viktor

+0

@Viktor問題はありません。答えを正しいとマークしてください。 – mitch

関連する問題