AJAX (Asynchronous JavaScript and XML) 是一种在不重新加载整个页面的情况下,与服务器交换数据并更新部分网页的技术。现代AJAX调用通常使用JSON格式而非XML。
var xhr = new XMLHttpRequest();
xhr.open('GET', 'your-api-endpoint', true);
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 300) {
var response = JSON.parse(xhr.responseText);
console.log(response.key); // 获取特定键的值
} else {
console.error('Request failed with status: ' + xhr.status);
}
};
xhr.onerror = function() {
console.error('Request failed');
};
xhr.send();
fetch('your-api-endpoint')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
console.log(data.key); // 获取特定键的值
})
.catch(error => {
console.error('There was a problem with the fetch operation:', error);
});
$.ajax({
url: 'your-api-endpoint',
type: 'GET',
dataType: 'json',
success: function(data) {
console.log(data.key); // 获取特定键的值
},
error: function(xhr, status, error) {
console.error('Error:', error);
}
});
axios.get('your-api-endpoint')
.then(function(response) {
console.log(response.data.key); // 获取特定键的值
})
.catch(function(error) {
console.error('Error:', error);
});
原因:
解决方案:
原因:
解决方案:
try {
var data = JSON.parse(response);
} catch (e) {
console.error('Invalid JSON:', e);
}
原因:
解决方案:
async function fetchData() {
try {
const response = await fetch('your-api-endpoint');
const data = await response.json();
console.log(data.key);
} catch (error) {
console.error('Error:', error);
}
}
fetchData();
没有搜到相关的文章