无法调用API并无法接收汇率

时间:2018-06-25 12:44:18

标签: javascript jquery

我目前正在学习Java,HTML和CSS,因此尽管我在调用API和打印相关数据(汇率)时遇到困难,但已经开始制作货币转换器以将这些技能结合在一起。下面是我的代码:

<html>
 <head>
  <title>API Test</title>
 </head>
 <body>
    <script>
    endpoint = 'latest'
    access_key = 'xxx';

// get the most recent exchange rates via the "latest" endpoint:
$.ajax({
    url: 'http://data.fixer.io/api/' + endpoint + '?access_key=' + access_key,   
    dataType: 'jsonp',
    success: function(json) {

        // exchange rata data is stored in json.rates
        alert(json.rates.GBP);

        // base currency is stored in json.base
        alert(json.base);

        // timestamp can be accessed in json.timestamp
        alert(json.timestamp);

    </script>
 </body>
</html>

以下代码根本不会打印任何内容,因此我不确定为什么这样做。上面的代码直接来自api文档,尽管作为一个初学者,我觉得我可能会遗漏一些明显的东西。对于为什么发生这种情况的任何帮助,将不胜感激。

1 个答案:

答案 0 :(得分:1)

@ Andy58,似乎是jquery函数关闭断点的问题,可能是您忘记了包含jquery,所以请尝试使用给定的html

<html>
 <head>
  <title>API Test</title>
  <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js">
</script>
 </head>
 <body>
    <script>
    endpoint = 'latest'
    access_key = 'xxx';

// get the most recent exchange rates via the "latest" endpoint:
$.ajax({
    url: 'http://data.fixer.io/api/' + endpoint + '?access_key=' + access_key,   
    dataType: 'json',
    success: function(json) {
        alert(json);
        // exchange rata data is stored in json.rates
        alert(json.rates.GBP);

        // base currency is stored in json.base
        alert(json.base);

        // timestamp can be accessed in json.timestamp
        alert(json.timestamp);
      }
      });
    </script>
 </body>
</html>