在 JavaScript 中,可以使用 `XMLHttpRequest` 对象或 `fetch` API 来发出 HTTP 请求。下面是使用这两种方法的示例代码:
## **使用 XMLHttpRequest 对象:**
```javascript
// 创建 XMLHttpRequest 对象
var xhr = new XMLHttpRequest();
// 设置请求方法和 URL
xhr.open('GET', 'https://api.example.com/data');
// 设置请求头
xhr.setRequestHeader('Content-Type', 'application/json');
// 监听请求状态变化
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
// 处理响应数据
var response = JSON.parse(xhr.responseText);
console.log(response);
}
};
// 发送请求
xhr.send();
```
## **使用 fetch API:**
```javascript
// 发送 GET 请求
fetch('https://api.example.com/data')
.then(function(response) {
if (response.ok) {
// 处理响应数据
return response.json();
} else {
throw new Error('Network response was not ok.');
}
})
.then(function(data) {
console.log(data);
})
.catch(function(error) {
console.log('There has been a problem with your fetch operation: ', error.message);
});
// 发送 POST 请求
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'John Doe',
email: 'johndoe@example.com'
})
})
.then(function(response) {
if (response.ok) {
// 处理响应数据
return response.json();
} else {
throw new Error('Network response was not ok.');
}
})
.then(function(data) {
console.log(data);
})
.catch(function(error) {
console.log('There has been a problem with your fetch operation: ', error.message);
});
```
以上代码中,我们使用了 `XMLHttpRequest` 对象和 `fetch` API 分别发送了 GET 和 POST 请求,并在响应成功时处理了响应数据。