Skip to content

AJAX 前言

学习如何通过在后台与服务器交换数据来使网页动态化和交互化,而无需重新加载整个页面。本教程重点介绍 Fetch API、Promises 和 async/await 等现代技术。

虽然传统上称为 AJAX(异步 JavaScript 和 XML),但现代实践强烈倾向于使用 JSON 而非 XML 作为数据格式,并使用 Fetch API 而非旧的 XMLHttpRequest 对象。

每章都包含演示概念的代码示例。您可以在自己的开发环境中调整并运行这些示例。

<button id="fetchBtn">Fetch Data</button>
<div id="output">Click button to load data...</div>
<script>
document.getElementById('fetchBtn').addEventListener('click', async () => {
const outputDiv = document.getElementById('output');
outputDiv.textContent = 'Loading...';
try {
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1'); // Example API
if (!response.ok) throw new Error(`HTTP error! Status: ${response.status}`);
const data = await response.json();
outputDiv.textContent = `Fetched Title: ${data.title}`;
} catch (error) {
outputDiv.textContent = `Error: ${error.message}`;
console.error('Fetch error:', error);
}
});
</script>

(注意:上面的示例使用了公共测试 API。请确保您有互联网连接才能尝试。)

立即开始学习现代异步 JavaScript!