DELETE 请求可以通过多种方式使用 Ajax 发送,以下是常见的几种方法:
const xhr = new XMLHttpRequest();
const url = 'https://api.example.com/users/123';
xhr.open('DELETE', url, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Authorization', 'Bearer token'); // 如果需要
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log('删除成功:', xhr.responseText);
} else {
console.error('删除失败:', xhr.status);
}
}
};
xhr.send();
fetch('https://api.example.com/users/123', {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer token' // 如果需要
}
})
.then(response => {
if (!response.ok) {
throw new Error('删除失败');
}
return response.json(); // 如果返回 JSON
})
.then(data => {
console.log('删除成功:', data);
})
.catch(error => {
console.error('错误:', error);
});
fetch('https://api.example.com/users/123', {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
reason: "用户请求删除"
}) // 有些 API 允许 DELETE 带请求体
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
$.ajax({
url: 'https://api.example.com/users/123',
type: 'DELETE',
contentType: 'application/json',
headers: {
'Authorization': 'Bearer token'
},
success: function(data) {
console.log('删除成功:', data);
},
error: function(xhr, status, error) {
console.error('删除失败:', error);
}
});
// 基本用法
axios.delete('https://api.example.com/users/123')
.then(response => {
console.log('删除成功:', response.data);
})
.catch(error => {
console.error('删除失败:', error);
});
// 带配置
axios.delete('https://api.example.com/users/123', {
headers: {
'Authorization': 'Bearer token'
},
data: { // 有些 API 需要请求体
reason: "用户请求删除"
}
})
.then(response => {
console.log('删除成功:', response.data);
});
// 或者使用配置对象方式
axios({
method: 'delete',
url: 'https://api.example.com/users/123',
headers: {
'Authorization': 'Bearer token'
},
data: {
reason: "用户请求删除"
}
});
async function deleteUser(userId) {
try {
const response = await fetch(`https://api.example.com/users/${userId}`, {
method: 'DELETE',
headers: {
'Authorization': 'Bearer token'
}
});
if (!response.ok) {
throw new Error('删除失败');
}
const result = await response.json();
console.log('删除成功:', result);
return result;
} catch (error) {
console.error('错误:', error);
throw error;
}
}
// 使用
deleteUser(123);
请求体:根据 HTTP/1.1 规范,DELETE 请求可以带请求体,但并非所有服务器都支持。具体取决于 API 设计。
响应状态码:
200 OK - 删除成功,返回响应体204 No Content - 删除成功,无响应体404 Not Found - 资源不存在跨域请求:如果是跨域请求,需要服务器设置 CORS 头:
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
安全考虑:删除操作通常是敏感的,建议:
async function deleteResource(url, data = {}, token = null) {
const config = {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
}
};
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
if (Object.keys(data).length > 0) {
config.body = JSON.stringify(data);
}
try {
const response = await fetch(url, config);
if (response.status === 204) {
return { success: true }; // 204 无内容
}
if (response.ok) {
const result = await response.json();
return { success: true, data: result };
}
throw new Error(`删除失败: ${response.status}`);
} catch (error) {
console.error('删除错误:', error);
return { success: false, error: error.message };
}
}
// 使用示例
deleteResource('https://api.example.com/users/123', null, 'your-token-here')
.then(result => {
if (result.success) {
console.log('删除成功');
} else {
console.error('删除失败:', result.error);
}
});
推荐使用 Fetch API 或 Axios,它们都是现代、标准化的方法,提供了更简洁的语法和更好的错误处理机制。