什么是AJAX?
AJAX(Asynchronous JavaScript and XML)是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。虽然名字中包含XML,但现代AJAX主要使用JSON格式。AJAX的核心是
XMLHttpRequest
对象(或现代的
fetch
API),它允许浏览器与服务器进行异步通信。
基础:GET和POST请求
GET请求
GET请求用于从服务器获取数据。它将参数包含在URL中,适合获取不敏感的数据。
使用XMLHttpRequest发送GET请求
// 创建XMLHttpRequest对象
var xhr = new XMLHttpRequest();
// 配置请求:方法(GET),URL,是否异步(true)
xhr.open(‘GET’, ‘https://api.example.com/data?param1=value1¶m2=value2’, true);
// 设置请求完成的回调函数
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 300) {
// 请求成功,处理响应数据
console.log('响应数据:', xhr.responseText);
var data = JSON.parse(xhr.responseText);
// 处理数据...
} else {
// 请求失败
console.error('请求失败:', xhr.status, xhr.statusText);
}
};
// 设置请求失败的回调函数
xhr.onerror = function() {
console.error('网络错误');
};
// 发送请求
xhr.send();
使用fetch API发送GET请求
fetch('https://api.example.com/data?param1=value1¶m2=value2')
.then(response => {
if (!response.ok) {
throw new Error(‘网络响应不正常’);
}
return response.json(); // 解析JSON数据
})
.then(data => {
console.log(‘数据:’, data);
// 处理数据…
})
.catch(error => {
console.error(‘请求出错:’, error);
});
POST请求
POST请求用于向服务器提交数据,通常用于创建新资源或提交表单数据。数据包含在请求体中,比GET更安全(但不是加密)。
使用XMLHttpRequest发送POST请求
var xhr = new XMLHttpRequest();
xhr.open(‘POST’, ‘https://api.example.com/submit’, true);
// 设置请求头,告诉服务器发送的是JSON数据
xhr.setRequestHeader(‘Content-Type’, ‘application/json’);
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 300) {
console.log('响应数据:', xhr.responseText);
var data = JSON.parse(xhr.responseText);
// 处理数据...
} else {
console.error('请求失败:', xhr.status, xhr.statusText);
}
};
xhr.onerror = function() {
console.error('网络错误');
};
// 准备要发送的数据
var data = {
name: "张三",
email: "zhangsan@example.com"
};
// 发送JSON字符串
xhr.send(JSON.stringify(data));
使用fetch API发送POST请求
fetch('https://api.example.com/submit', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: "张三",
email: "zhangsan@example.com"
})
})
.then(response => response.json())
.then(data => {
console.log(‘成功:’, data);
})
.catch(error => {
console.error(‘错误:’, error);
});
高级应用
1. 请求中止(Abort)
有时候我们需要中止一个正在进行的AJAX请求,比如用户切换页面或输入新的搜索词时。
使用XMLHttpRequest中止请求
var xhr = new XMLHttpRequest();
xhr.open(‘GET’, ‘https://api.example.com/data’, true);
xhr.onload = function() {
if (xhr.status === 0) { // 0表示请求被中止
console.log(‘请求被中止’);
} else {
console.log(‘响应数据:’, xhr.responseText);
}
};
// 发送请求
xhr.send();
// 在某个条件下中止请求(例如5秒后)
setTimeout(function() {
xhr.abort(); // 中止请求
}, 5000);
使用fetch API中止请求
// 创建AbortController
const controller = new AbortController();
const signal = controller.signal;
fetch(‘https://api.example.com/data’, {
signal: signal // 传入signal
})
.then(response => response.json())
.then(data => {
console.log(‘数据:’, data);
})
.catch(error => {
if (error.name === ‘AbortError’) {
console.log(‘请求被中止’);
} else {
console.error(‘错误:’, error);
}
});
// 在某个条件下中止请求(例如5秒后)
setTimeout(() => {
controller.abort(); // 中止请求
}, 5000);
2. 进度监控(Progress Monitoring)
对于大文件上传或下载,我们可能需要监控进度。
使用XMLHttpRequest监控上传进度
var xhr = new XMLHttpRequest();
xhr.open(‘POST’, ‘https://api.example.com/upload’, true);
// 监听上传进度
xhr.upload.onprogress = function(event) {
if (event.lengthComputable) {
var percent = (event.loaded / event.total) * 100;
console.log(‘上传进度: ‘ + percent.toFixed(2) + ‘%’);
// 更新UI显示进度…
}
};
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 300) {
console.log('上传完成:', xhr.responseText);
} else {
console.error('上传失败:', xhr.status);
}
};
// 创建一个大文件(模拟)
var bigData = new Blob(['这是一个大文件的内容...'], { type: 'text/plain' });
xhr.send(bigData);
使用fetch API监控下载进度
fetch API本身不直接支持进度监控,但可以通过
ReadableStream
实现:
async function fetchWithProgress(url) {
const response = await fetch(url);
const reader = response.body.getReader();
const contentLength = +response.headers.get('Content-Length');
let receivedLength = 0;
while (true) {
const { done, value } = await reader.read();
if (done) break;
receivedLength += value.length;
const percent = (receivedLength / contentLength) * 100;
console.log(`下载进度: ${percent.toFixed(2)}%`);
// 更新UI...
}
// 读取完整数据后,可以转换为文本或其他格式
// 这里需要重新读取数据,因为reader只能读取一次
// 实际应用中可能需要在循环中收集数据
return response;
}
fetchWithProgress('https://api.example.com/bigfile.zip')
.then(response => response.blob())
.then(data => {
console.log(‘下载完成’);
// 处理数据…
});
3. 并发请求控制
当需要同时发送多个请求时,需要控制并发数量,避免服务器压力过大或浏览器资源耗尽。
// 并发请求控制函数
async function fetchWithConcurrency(urls, maxConcurrency) {
const results = [];
const executing = [];
for (const url of urls) {
// 创建请求promise
const promise = fetch(url).then(response => response.json());
results.push(promise);
// 当有请求完成时,从executing中移除
const cleanUp = () => {
const index = executing.indexOf(promise);
if (index > -1) executing.splice(index, 1);
};
promise.then(cleanUp).catch(cleanUp);
// 添加到执行队列
executing.push(promise);
// 如果当前执行数量达到上限,等待其中一个完成
if (executing.length >= maxConcurrency) {
await Promise.race(executing);
}
}
// 等待所有请求完成
return Promise.all(results);
}
// 使用示例
const urls = [
‘https://api.example.com/data1’,
‘https://api.example.com/data2’,
‘https://api.example.com/data3’,
‘https://api.example.com/data4’,
‘https://api.example.com/data5’
];
fetchWithConcurrency(urls, 2)
.then(results => {
console.log(‘所有请求完成:’, results);
})
.catch(error => {
console.error(‘请求失败:’, error);
});
4. 请求重试机制
对于不稳定的网络环境,自动重试失败的请求可以提高用户体验。
// 带重试的fetch函数
async function fetchWithRetry(url, options = {}, maxRetries = 3, delay = 1000) {
for (let i = 0; i <= maxRetries; i++) {
try {
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return await response.json();
} catch (error) {
if (i === maxRetries) {
throw error; // 最后一次尝试失败,抛出错误
}
console.log(`请求失败,${delay}ms后重试... (${i + 1}/${maxRetries})`);
// 等待指定时间后重试
await new Promise(resolve => setTimeout(resolve, delay));
// 指数退避:每次重试延迟时间加倍
delay *= 2;
}
}
}
// 使用示例
fetchWithRetry(‘https://api.example.com/unstable’, {}, 3, 1000)
.then(data => {
console.log(‘成功获取数据:’, data);
})
.error => {
console.error(‘最终失败:’, error);
});
5. 请求缓存控制
对于不经常变化的数据,可以使用缓存来减少不必要的请求。
// 简单的请求缓存实现
const requestCache = new Map();
function fetchWithCache(url, options = {}, ttl = 60000) {
const cacheKey = JSON.stringify({ url, options });
const cached = requestCache.get(cacheKey);
// 检查缓存是否存在且未过期
if (cached && (Date.now() – cached.timestamp) < ttl) {
console.log('从缓存读取数据');
return Promise.resolve(cached.data);
}
// 发送新请求
return fetch(url, options)
.then(response => {
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
})
.then(data => {
// 存入缓存
requestCache.set(cacheKey, {
data: data,
timestamp: Date.now()
});
return data;
});
}
// 使用示例
// 第一次会发送请求
fetchWithCache(‘https://api.example.com/data’, {}, 60000)
.then(data => console.log(‘数据:’, data));
// 60秒内再次调用,会从缓存读取
fetchWithCache(‘https://api.example.com/data’, {}, 60000)
.then(data => console.log(‘数据:’, data));
常见问题解决方案
1. 跨域问题(CORS)
问题描述
:浏览器安全策略限制,AJAX请求只能访问同源(协议+域名+端口相同)的资源。
解决方案
:
服务器端设置CORS响应头
:
Access-Control-Allow-Origin
: 允许访问的源
Access-Control-Allow-Methods
: 兄许的HTTP方法
Access-Control-Allow-Headers
: 允许的请求头
// Node.js Express示例
app.use((req, res, next) => {
res.header(‘Access-Control-Allow-Origin’, ‘http://yourdomain.com’);
// 允许所有源(开发环境)
// res.header(‘Access-Control-Allow-Origin’, ‘*’);
res.header(‘Access-Control-Allow-Methods’, ‘GET, POST, PUT, DELETE, OPTIONS’);
res.header(‘Access-Control-Allow-Headers’, ‘Content-Type, Authorization’);
// 处理预检请求
if (req.method === ‘OPTIONS’) {
return res.sendStatus(200);
}
next();
});
使用代理服务器
:
前端请求同源的代理服务器,由代理服务器转发请求到目标服务器
例如:Nginx反向代理
JSONP(仅限GET请求,不推荐)
:
利用