当涉及到在JavaScript中调用API时,通常会使用Fetch API或者XMLHttpRequest。下面是一个简单的例子,演示了如何在JavaScript中使用Fetch API调用全速电竞基础数据接口(apiballs):
<!DOCTYPE html>
<html>
<head>
<title>API调用示例</title>
</head>
<body>
<button onclick="callAPI()">调用API</button>
<div id="api-response">
<!-- 这里将显示API的响应 -->
</div>
<script>
function callAPI() {
// 设置API终结点和您获得的API密钥
var api_endpoint = "https://api.apiballs.com/football/v3/matches";
var api_key = "your_api_key";
// 设置需要传递的参数
var param1 = "value1";
var param2 = "value2";
// 构建API请求URL
var url = new URL(api_endpoint);
url.searchParams.append('param1', param1);
url.searchParams.append('param2', param2);
// 发起API请求
fetch(url, {
headers: {
'Authorization': 'Bearer ' + api_key
}
})
.then(response => {
if (!response.ok) {
throw new Error('网络错误');
}
return response.json();
})
.then(data => {
// 处理API响应
document.getElementById("api-response").innerText = JSON.stringify(data);
})
.catch(error => {
// 处理API调用失败的情况
console.error('API调用失败:', error);
});
}
</script>
</body>
</html>
在上面的示例中,我们创建了一个简单的网页,其中包含一个按钮和一个用于显示API响应的空白div。
当点击按钮时,调用callAPI函数。该函数使用Fetch API发起了一个GET请求,带有适当的Authorization头和参数。在API响应返回后,我们将响应数据显示在id为"api-response"的元素中。