在HTML中,默认情况下,表单只支持GET和POST请求。但是,可以通过JavaScript来发送PUT和DELETE请求。以下是几种常见的方法:
function sendPutRequest(url, data) {
var xhr = new XMLHttpRequest();
xhr.open('PUT', url, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send(JSON.stringify(data));
}
function sendDeleteRequest(url) {
var xhr = new XMLHttpRequest();
xhr.open('DELETE', url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send();
}
async function sendPutRequest(url, data) {
try {
const response = await fetch(url, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
if (response.ok) {
const result = await response.json();
console.log(result);
}
} catch (error) {
console.error('Error:', error);
}
}
async function sendDeleteRequest(url) {
try {
const response = await fetch(url, {
method: 'DELETE'
});
if (response.ok) {
console.log('Success');
}
} catch (error) {
console.error('Error:', error);
}
}
import axios from 'axios';
function sendPutRequest(url, data) {
axios.put(url, data)
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error('Error:', error);
});
}
function sendDeleteRequest(url) {
axios.delete(url)
.then(response => {
console.log('Success');
})
.catch(error => {
console.error('Error:', error);
});
}
Content-Type
。通过以上方法,你可以在HTML中发送PUT和DELETE请求,并处理相应的响应。
领取专属 10元无门槛券
手把手带您无忧上云