2016-09-15 7 views
0

オープン天気APIからデータを取得しようとしていますが、使用できないオブジェクトがあります(JSONは内部ですがアクセスできません)何も返さない非常に単純なAPI呼び出し

私は非同期JSとコールバックについてたくさん読んだことがあります。私は実際に私が使用している各APIのコールバックが必要かどうか確信しています、私はすでに緯度と経度を取得するために使用しましたが、今はオープン天気APIのために、APIのパラメータとしてこれらのlatとlonを渡す必要があります(コールバック関数の引数は関数で使用されているものではなく、実際に返されたもので、私は非常に混乱していると思われます)、コールバックを使用するとどうすればよいか分かりません。

誰でも私がここで間違っていることを教えてもらえますか?

$(document).ready(function() { 
    $('#getWeather').on('click', function(){ 
    myLatAndLon(function(result) { 
     var lat = result[0]; 
     var lon = result[1]; 
     console.log(myWeather(lat, lon)); 
     // Here, although the params work in browser, the message that gets returned in console is : "NS_ERROR_DOM_BAD_URI: Access to restricted URI denied" 
    }); 
    }) 
}) 

function myLatAndLon(callback) { 
    $.getJSON('http://ip-api.com/json/').done(function(location) { 
    var arr = []; 
    arr.push(location.lat); 
    arr.push(location.lon); 
    callback(arr); 
    }); 
} 

function myWeather(lat, lon) { 
    return $.getJSON('http://api.openweathermap.org/data/2.5/weather', { 
     lat: lat, 
     lon: lon, 
     APPID: 'a9c241803382387694efa243346ec4d7' 
    }) 
    // The params are good, and when I type them on my browser, everything works fine 
} 
再度、テストに

EDIT : I'm adding a picture to make it clearer what I'm trying to do and what I get eventually

+1

URLの先頭に 'http://'を追加しようとしましたか? – WillardSolutions

+0

ねえ、はい、申し訳ありません、私は自分の投稿を編集しています。 オブジェクトを取得していますが、取得しようとするたびにJSONを取得できません。定義されていません... –

+1

JSONを解析しましたか? 「JSON.parse(returned_string);」 – WillardSolutions

答えて

1

変更してコードを: http://enable-cors.org/server.htmlを:

$(document).ready(function() { 
 
    $('#get').on('click', function() { 
 
    myLatAndLon(function(result) { 
 
     var lat = result[0]; 
 
     var lon = result[1]; 
 
     alert(JSON.stringify(result)); 
 
     $req = myWeather(lat, lon); 
 
     $req.done(function(R) { 
 
     alert(JSON.stringify(R)) 
 
     }); 
 
    }); 
 
    }) 
 
}) 
 

 
function myLatAndLon(callback) { 
 
    $.getJSON('//ip-api.com/json/').done(function(location) { 
 
    var arr = []; 
 
    arr.push(location.lat); 
 
    arr.push(location.lon); 
 
    callback(arr); 
 
    }); 
 
} 
 

 
function myWeather(lat, lon) { 
 
    return $.getJSON('//api.openweathermap.org/data/2.5/weather', { 
 
    lat: lat, 
 
    lon: lon, 
 
    APPID: 'a9c241803382387694efa243346ec4d7' 
 
    }) 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button id="get">get</button>

CORS制限はもっとここで読むためにあなたがあなたのサーバーをチェックする必要があります

+0

こんにちは、お返事ありがとう、私は試しましたが、残念ながら結果は変わりません。最後にJSONのオブジェクトを取得していますが、まだJSONにアクセスできません... –

+0

私はフィドルでテストを待ちます – MSS

+0

ありがとう、私はちょうどそれを明確にするために画像を追加しました –

関連する問題