js实现httpdelete
HTTP DELETE 请求的实现方法
在 JavaScript 中实现 HTTP DELETE 请求可以通过多种方式完成,以下是几种常见的方法:

使用原生 XMLHttpRequest
var xhr = new XMLHttpRequest();
xhr.open('DELETE', 'https://api.example.com/resource/123', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log('删除成功');
}
};
xhr.send();
使用 Fetch API
fetch('https://api.example.com/resource/123', {
method: 'DELETE',
headers: {
'Content-Type': 'application/json'
}
})
.then(response => {
if (!response.ok) {
throw new Error('删除失败');
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error(error));
使用 Axios 库
axios.delete('https://api.example.com/resource/123')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
使用 jQuery AJAX
$.ajax({
url: 'https://api.example.com/resource/123',
type: 'DELETE',
success: function(result) {
console.log('删除成功');
},
error: function(xhr, status, error) {
console.error(error);
}
});
注意事项
确保后端 API 支持 DELETE 方法,并正确处理请求。

根据实际需求添加适当的请求头和错误处理逻辑。
对于需要发送数据的 DELETE 请求,可以将数据放在请求体中或作为 URL 参数传递。
跨域请求需要服务器配置 CORS 头部信息。






