首页 > 解决方案 > 无法调用 API 和接收汇率

问题描述

我目前正在学习 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 文档,尽管作为初学者,我觉得我可能遗漏了一些明显的东西。任何有关为什么会发生这种情况的帮助将不胜感激。

标签: javascriptjquery

解决方案


@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>

推荐阅读