所以我刚开始使用Javascript,我想知道如何访问NASA API,例如https://api.nasa.gov/planetary/earth/assets?lon=100.75&lat=1.5&begin=2014-02-01&api_key=DEMO_KEY 并使用数据?我想得到“日期”并将它们放入一个数组中,但我不知道该怎么做。我怎么能用Javascript做到这一点?
答案 0 :(得分:1)
如果你正在使用jQuery,你可以使用jQuery.ajax(url)方法进行ajax调用,并传入'https://api.nasa.gov/planetary/earth/assets?lon=100.75&lat=1.5&begin=2014-02-01&api_key=DEMO_KEY'作为url。
编辑:这是更详细的代码/解释,在jquery中提出ajax请求:
$.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 :(得分: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);

答案 2 :(得分: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);
});
然后在控制台中,您可以看到结果。或者只是根据需要使用数组变量