AJAX请求示例:
- 使用原生JavaScript:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
console.log(response);
}
};
xhr.send();
- 使用Fetch函数:
fetch('https://api.example.com/data')
.then(function (response) {
return response.json();
})
.then(function (data) {
console.log(data);
})
.catch(function (error) {
console.log(error);
});
- 使用jQuery:
$.ajax({
url: 'https://api.example.com/data',
method: 'GET',
success: function (data) {
console.log(data);
},
error: function (error) {
console.log(error);
}
});
- 使用Axios:
axios.get('https://api.example.com/data')
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});