AJAX即异步JavaScript和XML,允许网页在不重新加载整个页面的情况下,与服务器交换数据并更新部分网页内容,是前端开发中常用的异步通信方案。JS发送AJAX请求有多种实现方式,不同方式的语法和适用场景有所差异。

一、原生XMLHttpRequest实现AJAX请求
XMLHttpRequest是最早的原生AJAX实现方式,所有现代浏览器都支持该对象,不需要依赖任何第三方库。
使用XMLHttpRequest发送GET请求的基本步骤如下:
- 创建XMLHttpRequest实例
- 调用open方法设置请求方法、请求地址和是否异步
- 监听onreadystatechange事件,判断请求状态
- 调用send方法发送请求
// 创建XMLHttpRequest实例
const xhr = new XMLHttpRequest();
// 设置请求方法和地址,true表示异步请求
xhr.open('GET', 'https://ipipp.com/api/user?id=1', true);
// 监听请求状态变化
xhr.onreadystatechange = function() {
// readyState为4表示请求完成,status为200表示请求成功
if (xhr.readyState === 4 && xhr.status === 200) {
const response = JSON.parse(xhr.responseText);
console.log('请求结果:', response);
}
};
// 发送请求
xhr.send();
如果需要发送POST请求,只需要在open时设置方法为POST,并在send中传入请求参数即可:
const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://ipipp.com/api/user', true);
// 设置请求头,指定参数格式为JSON
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log('请求成功:', xhr.responseText);
}
};
// 发送JSON格式的参数
const params = { name: '张三', age: 20 };
xhr.send(JSON.stringify(params));
二、Fetch API实现AJAX请求
Fetch API是ES6新增的原生网络请求接口,基于Promise设计,语法比XMLHttpRequest更简洁,是目前推荐的原生AJAX实现方式。
使用Fetch发送GET请求的示例如下:
// Fetch默认发送GET请求
fetch('https://ipipp.com/api/user?id=1')
.then(response => {
// 判断响应状态是否成功
if (!response.ok) {
throw new Error('请求失败,状态码:' + response.status);
}
// 解析响应为JSON格式
return response.json();
})
.then(data => {
console.log('请求结果:', data);
})
.catch(error => {
console.error('请求出错:', error);
});
发送POST请求的Fetch示例如下,需要手动设置method、headers和body参数:
fetch('https://ipipp.com/api/user', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name: '李四', age: 22 })
})
.then(response => response.json())
.then(data => {
console.log('新增用户结果:', data);
})
.catch(error => {
console.error('请求出错:', error);
});
三、jQuery ajax实现AJAX请求
jQuery库封装了ajax方法,语法简洁,兼容性较好,适合还在使用jQuery的老项目。
使用前需要先引入jQuery库,发送GET请求的示例如下:
$.ajax({
url: 'https://ipipp.com/api/user',
type: 'GET',
data: { id: 1 },
dataType: 'json',
success: function(response) {
console.log('请求成功:', response);
},
error: function(xhr, status, error) {
console.error('请求失败:', error);
}
});
发送POST请求的示例如下:
$.ajax({
url: 'https://ipipp.com/api/user',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ name: '王五', age: 25 }),
dataType: 'json',
success: function(response) {
console.log('新增成功:', response);
},
error: function(xhr, status, error) {
console.error('请求失败:', error);
}
});
四、axios库实现AJAX请求
axios是一个基于Promise的第三方HTTP库,支持浏览器和Node.js环境,语法简洁,功能丰富,是目前前端项目中最常用的AJAX请求库。
使用前需要先通过npm安装或者引入CDN,发送GET请求的示例如下:
// 发送GET请求
axios.get('https://ipipp.com/api/user?id=1')
.then(response => {
console.log('请求结果:', response.data);
})
.catch(error => {
console.error('请求出错:', error);
});
// 也可以把参数放在config中
axios.get('https://ipipp.com/api/user', {
params: { id: 1 }
}).then(response => {
console.log('请求结果:', response.data);
});
发送POST请求的示例如下:
axios.post('https://ipipp.com/api/user', {
name: '赵六',
age: 28
}, {
headers: { 'Content-Type': 'application/json' }
})
.then(response => {
console.log('新增成功:', response.data);
})
.catch(error => {
console.error('请求出错:', error);
});
四种方式的对比
不同AJAX实现方式的特点如下:
| 实现方式 | 优点 | 缺点 | 适用场景 |
|---|---|---|---|
| XMLHttpRequest | 原生支持,无需依赖 | 语法繁琐,回调嵌套,不支持Promise | 无第三方库依赖的场景 |
| Fetch API | 原生支持,基于Promise,语法简洁 | 默认不携带Cookie,错误处理需要手动判断 | 现代浏览器项目,无第三方库依赖场景 |
| jQuery ajax | 语法简单,兼容性好 | 需要依赖jQuery库,体积较大 | 使用jQuery的老项目 |
| axios | 语法简洁,支持拦截器、取消请求等功能,兼容性好 | 需要引入第三方库 | 现代前端项目,尤其是Vue、React项目 |
开发者可以根据项目的实际情况选择合适的AJAX请求实现方式,新项目推荐优先使用Fetch API或者axios库。
AJAXXMLHttpRequestFetch_APIjQuery_ajaxaxios修改时间:2026-07-04 10:06:32