Javascript 无法调用API并接收汇率
我目前正在学习Java、HTML和CSS,因此我开始制作一个货币转换器,将这些技能结合在一起,尽管我在调用API和打印相关数据(汇率)方面遇到了困难。下面是我的代码:Javascript 无法调用API并接收汇率,javascript,jquery,Javascript,Jquery,我目前正在学习Java、HTML和CSS,因此我开始制作一个货币转换器,将这些技能结合在一起,尽管我在调用API和打印相关数据(汇率)方面遇到了困难。下面是我的代码: <html> <head> <title>API Test</title> </head> <body> <script> endpoint = 'latest' access_key = 'xxx'; // g
<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测试
端点='最新'
访问密钥='xxx';
//通过“最新”端点获取最新汇率:
$.ajax({
网址:'http://data.fixer.io/api/“+endpoint+”?访问键=“+access\u键,
数据类型:“jsonp”,
成功:函数(json){
//exchange rata数据存储在json.rates中
警报(json.rates.GBP);
//基本货币存储在json.base中
警报(json.base);
//可以在json.timestamp中访问时间戳
警报(json.timestamp);
下面的代码根本不打印任何内容,我不确定这是为什么。上面的代码直接来自api文档,尽管作为一个初学者,我觉得我可能遗漏了一些明显的东西。任何关于为什么会出现这种情况的帮助都将不胜感激。@Andy58,jquery函数关闭breakets似乎有问题,可能是您忘记包含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>
API测试
端点='最新'
访问密钥='xxx';
//通过“最新”端点获取最新汇率:
$.ajax({
网址:'http://data.fixer.io/api/“+endpoint+”?访问键=“+access\u键,
数据类型:“json”,
成功:函数(json){
警报(json);
//exchange rata数据存储在json.rates中
警报(json.rates.GBP);
//基本货币存储在json.base中
警报(json.base);
//可以在json.timestamp中访问时间戳
警报(json.timestamp);
}
});
当您在页面中包含jQuery时,您的代码似乎工作正常:。仅供参考,我从不发布您的访问密钥。如果它们被滥用,可能会发生数据泄漏或服务滥用,您的帐户可能会被终止或阻止。另外,它们现在也处于混乱状态…!从您的代码片段中,您缺少一些右括号:一个右括号表示成功,另一个括号表示失败另一种方法是ajax方法。因此,您需要指定:}});语法和格式非常重要。