AJAX 示例
基本异步 JavaScript 示例(Fetch API)
Section titled “基本异步 JavaScript 示例(Fetch API)”让我们创建一个非常简单的示例,看看异步 JavaScript 如何使用现代 Fetch API 工作。我们将通过点击按钮从服务器上的文本文件加载内容。
目标:点击按钮,从 message.txt 获取文本内容,并将其显示在一个 div 中,而无需重新加载页面。
HTML 结构
Section titled “HTML 结构”首先,设置基本的 HTML 元素:一个用于存放内容的 div 和一个用于触发 Fetch 的 button。
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Basic Fetch Example</title> <style> #contentDiv { border: 1px solid #ccc; padding: 15px; margin-top: 10px; min-height: 50px; background-color: #f9f9f9; } </style></head><body>
<h1>Load Content Dynamically</h1>
<button id="loadButton">Load Message</button>
<div id="contentDiv"> <p>Click the button to load content from the server.</p></div>
<script src="app.js"></script> <!-- Link to our JavaScript file -->
</body></html>我们有:
- 一个 ID 为
loadButton的button。 - 一个 ID 为
contentDiv的div,用于显示获取的文本。 - 一个链接到
app.js的script标签,我们的 JavaScript 代码将放在这里。
服务器文件 (message.txt)
Section titled “服务器文件 (message.txt)”在同一目录下(或通过 URL 路径可访问的位置)创建一个名为 message.txt 的简单文本文件,包含一些内容:
Hello from the server! This content was loaded asynchronously using the Fetch API.JavaScript (app.js)
Section titled “JavaScript (app.js)”现在,让我们编写 JavaScript 代码来处理按钮点击并获取数据。
// Get references to the button and the content divconst loadButton = document.getElementById('loadButton');const contentDiv = document.getElementById('contentDiv');
// Define the function to fetch and display the dataasync function loadMessage() { contentDiv.innerHTML = '<p><i>Loading...</i></p>'; // Provide feedback
try { // Use fetch to request the content from message.txt const response = await fetch('message.txt');
// Check if the request was successful (status 200-299) if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); }
// Get the response body as text const messageText = await response.text();
// Update the content div with the fetched text contentDiv.textContent = messageText;
} catch (error) { // Handle any errors that occurred during fetch or processing console.error('Error loading message:', error); contentDiv.innerHTML = `<p style="color: red;">Failed to load message: ${error.message}</p>`; }}
// Add an event listener to the button// When the button is clicked, call the loadMessage functionloadButton.addEventListener('click', loadMessage);- 获取元素:我们使用按钮和 div 的 ID 获取它们的引用。
async function loadMessage():我们定义了一个async函数来包含我们的异步逻辑。- 加载反馈:我们立即更新
contentDiv以显示 ‘Loading…’ 消息。 fetch('message.txt'):这会发起一个针对指定文件的异步 HTTP GET 请求。await:await关键字会暂停loadMessage函数的执行,直到fetchPromise 解析(resolve)为一个Response对象。- 错误检查 (
response.ok):我们检查 HTTP 状态码是否表示成功。如果不成功,我们就抛出一个错误。 await response.text():如果响应正常,我们awaitresponse.text()方法,该方法返回另一个 Promise,它会解析为文件的实际文本内容。- 更新 DOM:一旦我们获取了
messageText,我们就更新contentDiv的textContent。 try...catch:整个获取过程都包裹在一个try...catch块中,用于处理潜在的错误(网络问题、文件未找到等)。如果发生错误,我们会记录错误并在contentDiv中显示错误消息。- 事件监听器:我们为
loadButton附加一个click事件监听器。点击时,它会执行loadMessage函数。
本示例演示了核心原则:发起异步请求、处理响应(包括潜在错误)以及在不完全重新加载页面的情况下动态更新网页。
后续章节将深入探讨如何配置请求、处理不同的数据类型(如 JSON)以及更有效地管理异步操作。