html调用api接口
时间: 2023-08-09 18:06:29 浏览: 81
要在HTML中调用API接口,你需要使用JavaScript来发起HTTP请求。以下是一个基本的例子:
```html
<!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) {
$("#result").html(data);
},
error: function(error) {
console.log(error);
}
});
});
});
</script>
</head>
<body>
<button id="btn">获取数据</button>
<div id="result"></div>
</body>
</html>
```
在这个例子中,我们使用jQuery的$.ajax()函数来发起GET请求。我们指定了API的URL,指定了数据类型为JSON,并定义了成功和失败的回调函数。当用户点击按钮时,我们会发起请求并在成功时显示返回的数据。这只是一个基本的例子,你可以根据需要进行修改和扩展。