JavaScript请求http
时间: 2023-09-14 21:02:29 浏览: 36
在 JavaScript 中,可以使用 XMLHttpRequest 对象来发送 HTTP 请求。该对象可以通过以下步骤创建和使用:
1. 创建 XMLHttpRequest 对象
```
var xhr = new XMLHttpRequest();
```
2. 设置请求的方式、URL 和是否异步
```
xhr.open('GET', 'http://example.com', true);
```
3. 设置请求头
```
xhr.setRequestHeader('Content-Type', 'application/json');
```
4. 监听请求状态变化
```
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.error('请求失败');
}
}
};
```
5. 发送请求
```
xhr.send();
```
完整的请求示例:
```
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://example.com', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.error('请求失败');
}
}
};
xhr.send();
```