2016-10-19 2 views
0

Javascriptを使い慣れていないので、https://api.nasa.gov/planetary/earth/assets?lon=100.75&lat=1.5&begin=2014-02-01&api_key=DEMO_KEY などのNASA APIにアクセスしてデータを使用する方法が不思議です。私は、 "日付"を取得し、配列に入れたいが、私はそれを行う方法がわからない。 Javascriptを使ってどうすればいいですか?Javascriptを使ってNASA APIにアクセスする

+1

多分[このQ&A](https://stackoverflow.com/questions/38881388/javascript-http-request-failed)のコード –

答えて

1

jQueryを使用している場合は、jQuery.ajax(url)メソッドを使用し、URLとして 'https://api.nasa.gov/planetary/earth/assets?lon=100.75&lat=1.5&begin=2014-02-01&api_key=DEMO_KEY'を渡してajax呼び出しを行うことができます。

EDIT:これはjqueryのでAJAXリクエストをfodoingより詳細なコード/、について説明です:

$.ajax({ 

    // The URL for the request 
    url: "https://api.nasa.gov/planetary/earth/assets?lon=100.75&lat=1.5&begin=2014-02-01&api_key=DEMO_KEY", 


    // Whether this is a POST or GET request 
    type: "GET", 

    // The type of data we expect back 
    dataType : "json", 
}) 
    // Code to run if the request succeeds (is done); 
    // The response is passed to the function 
    .done(function(json) { 
    console.log(json) 
    }) 
    // Code to run if the request fails; the raw request and 
    // status codes are passed to the function 
    .fail(function(xhr, status, errorThrown) { 
    alert("Sorry, there was a problem!"); 
    console.log("Error: " + errorThrown); 
    console.log("Status: " + status); 
    console.dir(xhr); 
    }) 
    // Code to run regardless of success or failure; 
    .always(function(xhr, status) { 
    alert("The request is complete!"); 
    }); 
1

のAjaxについての記事を読むthis guide from MDN。次に、JSON.parseを使用して返されたデータを解析し、次にmap()を使用して結果配列の各項目から日付を取得できます。以下の例を参照してください。 jQueryのようなライブラリを使用する場合は、AJAXコードを簡略化します。

var url = 'https://api.nasa.gov/planetary/earth/assets?lon=100.75&lat=1.5&begin=2014-02-01&api_key=DEMO_KEY'; 
 
var httpRequest; //declare here for good scope 
 
if (window.XMLHttpRequest) { // Mozilla, Safari, IE7+ ... 
 
    httpRequest = new XMLHttpRequest(); 
 
} else if (window.ActiveXObject) { // IE 6 and older 
 
    httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); 
 
} 
 
httpRequest.onreadystatechange = function() { 
 
    if (httpRequest.readyState === XMLHttpRequest.DONE && httpRequest.status == 200) { 
 
    returnedData = httpRequest.responseText; 
 
    var data = JSON.parse(returnedData); 
 
    if (data.hasOwnProperty('results')) { 
 
     var dates = data.results.map(function(result) { 
 
     return result.date; 
 
     }); 
 
     console.log('dates: ',dates); 
 
    } 
 
    } else { 
 
    // still not ready or error occurred 
 
    } 
 
}; 
 
httpRequest.open('GET', url, true); 
 
httpRequest.send(null);

+1

よく理解するにはこのコードはあなたが[JavaScriptのコールバック](http://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/)を理解したいと思っていますし、モダンを使ってきれいな非同期コードを書いてパターンを理解し、[JavaScriptの約束](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)を使用してください。コールバック/約束は、HTTPリクエストがデータを返すまでの正確な時間を知らないので必要です。彼らは "あなたが応答を得たらすぐにこれをしなさい"と言う方法です。 – Skylar

+1

リソース@Skylarをありがとう - 一部のブラウザ(主にIE)はプロミスをネイティブにサポートしていないことに注意してください([ブラウザの互換性](https://developer.mozilla.org/en-US/docsを参照)/Web/JavaScript/Reference/Global_Objects/Promise#Browser_compatibility)セクションを参照してください)。私はまた、非同期コードとコールバック(主に演習34-5)について言及しているこの[JSプログラミングの機能プログラミング](http://reactivex.io/learnrx/)(および練習を完了すること)を読むことをお勧めします。 –

+0

同僚も共有http://youmightnotneedjquery.com/ - jQuery、[reqwest](https://github.com/ded/Reqwest)、[then-request](httpsのオーバーヘッドのすべてを追加せずに約束を使用したい場合は、 ://github.com/then/then-request)look _promising_(すみませんでした)...私は彼らが良いオプションのように見えることを意味します –

0

jQueryを使って、このようにそれを使用してみてください:

var array = []; 
$.get('https://api.nasa.gov/planetary/earth/assets?lon=100.75&lat=1.5&begin=2014-02-01&api_key=DEMO_KEY',function(data){ 
     for(var i=0; i< data.results.length; i++) { 
     array.push(data.results[i].date); 
     } 
    console.log(array); 
}); 

次にコンソールにあなたは結果を見ることができます。または、あなたのニーズに配列変数を使用してください

+0

どのように日付を使用できますか? 2つの日付を加算するか減算するか? – John

+0

あなたはindex-array [i]でデータにアクセスすることができます - ここでiはインデックスです。または、配列に必要な値を検索します。私は現在何が必要なのか分かりません。配列にデータを追加するには〜array.push(data) - 配列の最後に追加します – Vyacheslav

関連する問題