帮我写一段能调用API的基于HTML和javascript的代码
时间: 2023-04-05 16:01:02 浏览: 61
好的,以下是基于HTML和JavaScript的调用API的代码示例:
```
<!DOCTYPE html>
<html>
<head>
<title>调用API示例</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("#btn").click(function(){
$.ajax({
url: "https://api.example.com/data",
type: "GET",
dataType: "json",
success: function(data){
console.log(data);
$("#result").html(JSON.stringify(data));
},
error: function(jqXHR, textStatus, errorThrown){
console.log(textStatus, errorThrown);
$("#result").html("请求失败:" + textStatus + " " + errorThrown);
}
});
});
});
</script>
</head>
<body>
<h1>调用API示例</h1>
<button id="btn">点击调用API</button>
<div id="result"></div>
</body>
</html>
```
这段代码使用了jQuery库,通过ajax方法向API发送GET请求,并将返回的数据显示在页面上。你可以根据自己的需求修改url、type、dataType等参数,以及处理返回数据的方式。