【问题标题】:Accessing NASA api using Javascript [closed]使用 Javascript 访问 NASA api [关闭]
【发布时间】:2016-10-20 07:49:10
【问题描述】:

所以我是使用 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 做到这一点?

【问题讨论】:

标签: javascript arrays json


【解决方案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!" );
  });

【讨论】:

    【解决方案2】:

    阅读this guide from MDN 了解 Ajax。然后您可以使用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);

    【讨论】:

    • 要很好地理解这段代码在做什么,你需要理解callbacks in JavaScript,如果你想使用现代模式编写干净的异步代码,你应该尝试理解并使用JavaScript promises。回调/承诺是必要的,因为您不确切知道 http 请求需要多长时间才能返回它的数据。它们是一种表达方式,即“得到回复后立即执行此操作。”。
    • 感谢@Skylar 提供的资源-尽管应该注意某些浏览器(主要是 IE)本身不支持 Promises(请参阅Browser Compatibility 部分),所以如果必须支持客户使用他们应该相应地调整任何那些较旧的浏览器。我还建议阅读这个Functional Programming in JS page(并完成练习),其中还提到了异步代码和回调(主要是练习 34-5)
    • 一位同事也与我分享了@98​​7654329@ - 如果你想在不增加 jQuery 的所有开销的情况下使用 Promise,reqwestthen-request 看看 promising (对不起,我不得不)...我的意思是它们看起来是不错的选择
    【解决方案3】:

    尝试像这样使用它,用 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);
    });
    

    然后在控制台中你可以看到结果。或者只是根据需要使用数组变量

    【讨论】:

    • 如何使用日期?比如加减两个日期?
    • 您可以使用索引访问数据 - array[i] - 其中 i 是索引。或者在数组中搜索所需的值。不知道你现在需要什么。也将数据添加到数组 - array.push(data) - 它将添加到数组的末尾
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-04
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 2011-09-24
    • 2013-03-18
    相关资源
    最近更新 更多