.js文件如何调用api
时间: 2024-10-10 19:06:55 浏览: 29
在JavaScript中,调用API通常涉及到网络请求。最常见的方法是使用XMLHttpRequest (XHR)对象或者更现代的Fetch API。以下是基本步骤:
1. **使用XMLHttpRequest**:
```javascript
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onload = function () {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.error('Error:', xhr.statusText);
}
};
xhr.send();
```
2. **使用Fetch API**:
```javascript
fetch('https://api.example.com/data')
.then(response => response.text())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
```
3. **Promise 或 async/await**:
使用async/await可以使代码看起来更简洁:
```javascript
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
} catch (error) {
console.error('There was a problem:', error);
}
}
fetchData().then(data => console.log(data));
```
记得替换`https://api.example.com/data`为实际的API地址。
阅读全文
相关推荐

















