温馨提示:这篇文章已超过239天没有更新,请注意相关的内容是否还可用!
1、当我们使用Ajax进行请求时,服务器会根据请求头中的Content-Type来判断接收到的数据的格式。如果请求头中的Content-Type与服务器期望的数据格式不匹配,服务器就会返回415状态码,表示不支持该媒体类型。
示例代码如下:
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://example.com/api', true);
xhr.setRequestHeader('Content-Type', 'application/json'); // 设置请求头的Content-Type为application/json
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log('请求成功');
} else if (xhr.status === 415) {
console.log('不支持该媒体类型');
} else {
console.log('请求失败');
}
}
};
xhr.send('{"name": "John", "age": 30}'); // 发送一个JSON格式的数据
在上面的示例代码中,我们使用XMLHttpRequest对象发送了一个POST请求到"http://example.com/api"。在设置请求头时,我们将Content-Type设置为"application/json",表示我们要发送的数据是JSON格式的。如果服务器不支持接收JSON格式的数据,就会返回415状态码。我们通过xhr.status来判断服务器返回的状态码,如果是415,则表示不支持该媒体类型。