不使用XMLHttpRequest发送HTTP请求的解决方法之一是使用Fetch API。
Fetch是一种现代的Web API,它提供了一种更简单和更强大的方式来发送HTTP请求。
以下是使用Fetch API发送GET请求的示例代码:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
以下是使用Fetch API发送POST请求的示例代码:
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name: 'John', age: 30 })
})
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
Fetch API使用Promise来处理响应,可以通过.then()方法链式调用来处理成功的响应,通过.catch()方法来处理错误。
请注意,Fetch API在一些旧版本的浏览器中可能不支持,但可以通过使用Polyfill或使用第三方库(如Axios)来解决兼容性问题。