在Web前端开发中,Javascript发起网络请求是实现前后端数据交互的核心能力,常见的实现方式有XMLHttpRequest、fetch API等,不同的方式有不同的特性和适用场景。

XMLHttpRequest发起网络请求
XMLHttpRequest是最早的Javascript原生网络请求方式,所有现代浏览器都支持,兼容性较好,适合需要兼容旧浏览器的场景。
基本使用步骤
- 创建XMLHttpRequest实例
- 配置请求方法、请求地址、是否异步
- 监听请求状态变化,处理响应结果
- 发送请求
代码示例
// 创建XMLHttpRequest实例
const xhr = new XMLHttpRequest();
// 配置请求,第一个参数是请求方法,第二个是请求地址,第三个表示是否异步
xhr.open('GET', 'https://ipipp.com/api/user/list', true);
// 监听状态变化
xhr.onreadystatechange = function() {
// readyState为4表示请求完成,status为200表示请求成功
if (xhr.readyState === 4 && xhr.status === 200) {
const response = JSON.parse(xhr.responseText);
console.log('请求结果:', response);
} else if (xhr.readyState === 4) {
console.error('请求失败,状态码:', xhr.status);
}
};
// 发送请求
xhr.send();
发送POST请求示例
const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://ipipp.com/api/user/add', true);
// 设置请求头,指定发送的数据格式为JSON
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log('添加成功:', JSON.parse(xhr.responseText));
}
};
// 发送JSON格式的数据,需要先转为字符串
const postData = JSON.stringify({ name: '张三', age: 20 });
xhr.send(postData);
fetch API发起网络请求
fetch是ES6新增的原生网络请求API,基于Promise实现,语法更简洁,支持async/await,是目前主流的开发方式,不过需要注意fetch默认不会携带Cookie,需要手动配置。
基本GET请求示例
// 使用then链式调用处理响应
fetch('https://ipipp.com/api/user/list')
.then(response => {
// 先判断响应是否成功,response.ok为true表示状态码在200-299之间
if (!response.ok) {
throw new Error('请求失败,状态码:' + response.status);
}
// 调用json()方法解析响应为JSON格式,返回的是Promise
return response.json();
})
.then(data => {
console.log('请求结果:', data);
})
.catch(error => {
console.error('请求出错:', error);
});
使用async/await优化代码
async function getUserList() {
try {
const response = await fetch('https://ipipp.com/api/user/list');
if (!response.ok) {
throw new Error('请求失败,状态码:' + response.status);
}
const data = await response.json();
console.log('请求结果:', data);
} catch (error) {
console.error('请求出错:', error);
}
}
getUserList();
发送POST请求示例
async function addUser() {
try {
const response = await fetch('https://ipipp.com/api/user/add', {
method: 'POST', // 指定请求方法
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name: '李四', age: 22 }), // 请求体数据
credentials: 'include' // 携带Cookie,可选same-origin、omit
});
if (!response.ok) {
throw new Error('请求失败,状态码:' + response.status);
}
const data = await response.json();
console.log('添加成功:', data);
} catch (error) {
console.error('请求出错:', error);
}
}
addUser();
两种方式的对比
我们可以通过表格对比两种原生请求方式的核心差异:
| 对比项 | XMLHttpRequest | fetch API |
|---|---|---|
| 语法风格 | 基于事件回调 | 基于Promise,支持async/await |
| 兼容性 | 兼容所有浏览器,包括旧版本 | 不支持IE,现代浏览器都支持 |
| Cookie携带 | 默认携带同源Cookie | 默认不携带,需要配置credentials参数 |
| 错误处理 | 需要判断status和readyState | 只有网络错误才会进入catch,HTTP错误状态码不会 |
注意事项
- 网络请求存在跨域限制,如果是跨域请求,需要后端配置CORS相关的响应头,否则请求会被浏览器拦截
- 请求地址如果是本地开发环境,127.0.0.1和192.168.0.1可以直接使用,不需要额外处理
- 发送JSON数据时,一定要设置
Content-Type请求头为application/json,否则后端可能无法正确解析数据 - 处理响应时,要根据后端返回的数据格式选择对应的解析方法,比如json()、text()、blob()等
JavascriptXMLHttpRequestfetchAjax修改时间:2026-06-29 01:42:28