js文件内怎么请求接口
时间: 2024-04-13 14:26:43 浏览: 7
在 JavaScript 文件中,你可以使用 XMLHttpRequest 或者 Fetch API 来发送请求并获取接口的数据。
使用 XMLHttpRequest 实现请求接口的代码如下:
```javascript
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://example.com/api', true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
// 处理接口返回的数据
}
};
xhr.send();
```
使用 Fetch API 实现请求接口的代码如下:
```javascript
fetch('http://example.com/api')
.then(function(response) {
if (response.ok) {
return response.json();
}
throw new Error('Network response was not ok.');
})
.then(function(data) {
// 处理接口返回的数据
})
.catch(function(error) {
console.log('There has been a problem with your fetch operation: ', error.message);
});
```
这两种方法都可以发送 GET 请求,对于 POST 请求,你需要在 `open` 方法中指定请求的方法为 "POST",并且在 `send` 方法中传递需要发送的数据。
同时,如果你使用的是现代的 JavaScript 环境,也可以考虑使用更加方便的工具库,比如 Axios 或者 Fetch API 的封装库。