要使用Ajax發(fā)送HTTP請求,可以使用JavaScript的XMLHttpRequest
對象或者更現(xiàn)代的fetch
API。下面是兩種方法的示例:
1. 使用XMLHttpRequest
對象:
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.example.com/data", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
}
};
xhr.send();
2. 使用fetch
API:
fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));