1. 原生XMLHttpRequest(传统方式)
// 创建XMLHttpRequest对象
var xhr = new XMLHttpRequest();
// 配置请求
xhr.open('GET', 'https://api.example.com/data', true); // true表示异步
// 设置请求头(如果需要)
xhr.setRequestHeader('Content-Type', 'application/json');
// 定义回调函数
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) { // 请求完成
if (xhr.status === 200) { // 请求成功
var response = JSON.parse(xhr.responseText);
console.log('成功:', response);
} else {
console.error('请求失败:', xhr.status);
}
}
};
// 发送请求
xhr.send();
// 发送POST请求(带数据)
xhr.open('POST', 'https://api.example.com/data', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({ key: 'value' }));
2. 使用Fetch API(现代方式)
// 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);
});
// POST请求
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer token123' // 如果需要认证
},
body: JSON.stringify({
name: '张三',
age: 25
})
})
.then(response => response.json())
.then(data => console.log('成功:', data))
.catch(error => console.error('失败:', error));
// 使用async/await
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log('成功:', data);
return data;
} catch (error) {
console.error('请求失败:', error);
}
}
3. 使用jQuery
// GET请求
$.ajax({
url: 'https://api.example.com/data',
method: 'GET',
dataType: 'json',
success: function(data) {
console.log('成功:', data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.error('失败:', textStatus, errorThrown);
}
});
// 简写方式
$.get('https://api.example.com/data', function(data) {
console.log('成功:', data);
});
// POST请求
$.ajax({
url: 'https://api.example.com/data',
method: 'POST',
contentType: 'application/json',
data: JSON.stringify({ name: '张三', age: 25 }),
success: function(response) {
console.log('成功:', response);
},
error: function(error) {
console.error('失败:', error);
}
});
// 使用Promise
$.ajax({
url: 'https://api.example.com/data',
method: 'GET'
})
.then(function(data) {
console.log('成功:', data);
})
.catch(function(error) {
console.error('失败:', error);
});
4. 发送不同类型的数据
// FormData(文件上传)
const formData = new FormData();
formData.append('file', fileInput.files[0]);
formData.append('username', '张三');
fetch('/upload', {
method: 'POST',
body: formData
});
// URL编码数据
const params = new URLSearchParams();
params.append('name', '张三');
params.append('age', '25');
fetch('/api/data', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: params
});
5. 封装可重用的Ajax函数
// 封装Fetch请求
class ApiService {
constructor(baseURL) {
this.baseURL = baseURL;
}
async request(endpoint, options = {}) {
const url = `${this.baseURL}${endpoint}`;
const defaultOptions = {
headers: {
'Content-Type': 'application/json',
},
credentials: 'include' // 包含cookie
};
try {
const response = await fetch(url, { ...defaultOptions, ...options });
if (!response.ok) {
throw new Error(`HTTP错误 ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('API请求失败:', error);
throw error;
}
}
get(endpoint) {
return this.request(endpoint, { method: 'GET' });
}
post(endpoint, data) {
return this.request(endpoint, {
method: 'POST',
body: JSON.stringify(data)
});
}
put(endpoint, data) {
return this.request(endpoint, {
method: 'PUT',
body: JSON.stringify(data)
});
}
delete(endpoint) {
return this.request(endpoint, { method: 'DELETE' });
}
}
// 使用示例
const api = new ApiService('https://api.example.com');
api.get('/users')
.then(data => console.log(data))
.catch(error => console.error(error));
注意事项:
跨域问题:确保后端已配置CORS(跨域资源共享)
错误处理:始终添加错误处理逻辑
安全性:敏感数据使用HTTPS,不要在前端硬编码密钥
加载状态:添加加载指示器提升用户体验
超时处理:为请求设置合理的超时时间
取消请求:使用AbortController(Fetch API)或abort()(XHR)取消请求
现代前端开发中,推荐使用Fetch API或axios(第三方库),因为它们提供了更简洁的语法和更好的错误处理机制。