如何通过ajax与fetch发送请求数据
·
摘要:本文对比了浏览器端两种核心的 HTTP 请求方式:传统 Ajax(XMLHttpRequest)与现代 Fetch API。文章分别演示了 GET 与 POST 请求的写法,并介绍了使用 async/await 让异步代码更简洁优雅的实践方式。
在Web开发中,Fetch API 和 Ajax (XMLHttpRequest) 是两种最核心的浏览器端发送HTTP请求的方式。
一、传统 Ajax
1. 基本用法(GET请求)
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
// 监听状态变化
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(JSON.parse(xhr.responseText));
}
};
// 发送请求
xhr.send();
2. 发送POST请求(带JSON数据)
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://api.example.com/submit', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
if (xhr.status === 200) {
console.log('成功:', xhr.responseText);
}
};
var data = JSON.stringify({ name: '张三', age: 25 });
xhr.send(data);
二、现代 Fetch API
Fetch 是基于 Promise 的新标准,语法更简洁,更符合现代JavaScript风格。
1. 基本 GET 请求
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('网络响应异常');
}
return response.json(); // 解析JSON
})
.then(data => console.log(data))
.catch(error => console.error('请求失败:', error));
2. 发送 POST 请求(JSON数据)
fetch('https://api.example.com/submit', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer your-token' // 携带认证信息
},
body: JSON.stringify({ name: '张三', age: 25 })
})
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));
注意这里,body传过去的是字符串
当然,以上fetch发送请请求后,.then .then .catch 看起来很难受,也像可以这样写
3.使用 async/await(更优雅)
async function sendData() {
const response = await fetch('https://api.example.com/submit', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: '张三' })
});
const result = await response.json();
console.log(result);
}
更多推荐

所有评论(0)