jQuery Get/Post 方法
jQuery - 使用 $.get() 和 $.post() 进行现代 AJAX
Section titled “jQuery - 使用 $.get() 和 $.post() 进行现代 AJAX”学习如何使用 jQuery 的 $.get() 和 $.post() 方法异步地(asynchronously)从服务器获取数据,并利用现代最佳实践。
AJAX (Asynchronous JavaScript and XML) 允许网页在不干扰现有页面显示和行为的情况下,通过在后台与服务器交换数据来实现动态更新。
HTTP 请求方法: GET vs. POST
Section titled “HTTP 请求方法: GET vs. POST”客户端-服务器通信的两个基本 HTTP 方法是 GET 和 POST:
- GET: 用于从指定资源请求数据。GET 请求应该是幂等的(idempotent,多次执行相同的请求结果相同),并且不应该产生副作用(它们不改变服务器状态)。
- POST: 用于向指定资源提交待处理的数据。POST 请求通常会导致服务器状态改变或产生副作用(例如,创建新记录、更新数据)。它们不是幂等的。
主要区别:
- 缓存(Caching): 浏览器可能会缓存 GET 请求的响应。POST 请求通常不会被缓存。
- 数据提交: GET 将数据附加到 URL 中(查询字符串 query string),数据可见且长度受限。POST 在请求体(request body)中发送数据,适合传输较大或敏感的数据。
- 使用场景: GET 用于检索数据(例如,获取文章、搜索结果)。POST 用于改变数据的操作(例如,提交表单、上传文件)。
为了更深入地了解 HTTP 方法,请参考 MDN Web 文档: HTTP request methods。
jQuery 的 $.get() 方法
Section titled “jQuery 的 $.get() 方法”$.get() 方法使用 HTTP GET 请求从服务器请求数据。它是功能更丰富的 $.ajax() 方法的简写形式。
现代语法 (使用 Promises):
$.get(URL, [data], [dataType]) .done(function(data, status, jqXHR) { // Request succeeded! Process the data. }) .fail(function(jqXHR, status, errorThrown) { // Request failed! Handle the error. }) .always(function() { // This function executes regardless of success or failure. });参数:
- URL: (必需) 请求数据的 URL 地址。
- data: (可选) 与请求一起发送到服务器的对象或字符串。
- dataType: (可选) 期望从服务器返回的数据类型(例如,‘json’、‘xml’、‘html’、‘text’)。jQuery 通常会自动推断。
Promise 接口 (.done(), .fail(), .always()):
- .done(function(data, status, jqXHR)): 请求成功时执行。
data包含响应数据,status是文本字符串(例如,‘success’),jqXHR是 jQuery XMLHttpRequest 对象。 - .fail(function(jqXHR, status, errorThrown)): 请求失败时执行。
status可能是 ‘error’、‘timeout’ 等,errorThrown包含错误消息。 - .always(function()): 无论请求成功或失败,都会执行。常用于清理任务(例如,隐藏加载指示器)。
示例: 从一个假设的 API 获取 JSON 数据:
$("#loadDataButton").click(function() { const apiUrl = "https://api.example.com/users/1"; // 示例 API 端点
$.get(apiUrl, { format: 'json' }) .done(function(userData, textStatus) { console.log("用户数据:", userData); console.log("状态:", textStatus); alert(`成功获取用户: ${userData.name}`); // 使用 userData 更新页面,例如: // $("#userInfo").text(`姓名: ${userData.name}, 邮箱: ${userData.email}`); }) .fail(function(jqXHR, textStatus, errorThrown) { console.error("AJAX 错误:", textStatus, errorThrown); alert(`获取数据出错: ${errorThrown || textStatus}`); }) .always(function() { console.log("AJAX 请求完成。"); // 例如,隐藏加载指示器 });});此示例假设位于 https://api.example.com/users/1 的 API 返回 JSON 数据,例如: {"id": 1, "name": "Alice", "email": "alice@example.com"}。
jQuery 的 $.post() 方法
Section titled “jQuery 的 $.post() 方法”$.post() 方法使用 HTTP POST 请求将数据发送到服务器。它也是 $.ajax() 的简写。
现代语法 (使用 Promises):
$.post(URL, [data], [dataType]) .done(function(data, status, jqXHR) { // Request succeeded! Process the response. }) .fail(function(jqXHR, status, errorThrown) { // Request failed! Handle the error. }) .always(function() { // Always executed. });参数与 $.get() 类似,但这里的 data 参数通常用于在请求体中向服务器发送信息。
示例: 以 JSON 格式提交表单数据:
$("#submitFormButton").click(function() { const formUrl = "https://api.example.com/users"; // 示例 API 端点,用于创建用户 const userData = { name: $("#userNameInput").val(), city: $("#userCityInput").val() };
// jQuery 会自动序列化对象并设置正确的 content type $.post(formUrl, JSON.stringify(userData), 'json') // 如果 API 需要原始 JSON,则明确地 stringify 并设置 dataType // 或者简单地: $.post(formUrl, userData) // 如果服务器期望 form-urlencoded 数据 .done(function(response, textStatus) { console.log("服务器响应:", response); console.log("状态:", textStatus); alert(`服务器响应: ${response.message}`); // 例如,显示成功消息,清除表单 }) .fail(function(jqXHR, textStatus, errorThrown) { console.error("AJAX 错误:", textStatus, errorThrown); alert(`提交数据出错: ${errorThrown || textStatus}`); }) .always(function() { console.log("AJAX 请求完成。"); });});此示例假设位于 https://api.example.com/users 的 API 接受包含 JSON 数据(例如 {"name": "Bob", "city": "Metropolis"})的 POST 请求,并返回类似 {"message": "User created successfully", "userId": 101} 的 JSON 响应。
数据格式说明: 虽然 jQuery 通常可以自动处理数据序列化(例如将 JavaScript 对象作为 form-urlencoded 数据发送),但现代 API 通常期望 JSON 格式。如果使用更通用的 $.ajax() 方法,你可能需要对数据使用 JSON.stringify() 并设置 contentType: 'application/json'。
$.ajax() 方法
Section titled “$.ajax() 方法”为了更精细地控制 AJAX 请求(例如,设置特定请求头 headers、使用 PUT 或 DELETE 等其他 HTTP 方法、详细的错误处理),请使用 $.ajax() 方法。$.get() 和 $.post() 都是对 $.ajax() 的封装(wrapper)。
示例: 使用 $.ajax() 发送 POST 请求:
$.ajax({ url: 'https://api.example.com/data', method: 'POST', // or type: 'POST' contentType: 'application/json', data: JSON.stringify({ key: 'value' }), dataType: 'json' // Expected response type}).done(function(response) { console.log('Success:', response);}).fail(function(jqXHR, textStatus, errorThrown) { console.error('Error:', textStatus, errorThrown);});现代替代方案: Fetch API
Section titled “现代替代方案: Fetch API”虽然 jQuery 的 AJAX 方法很方便,但现代 JavaScript 提供了内置的 Fetch API。它基于 Promise,为发起网络请求提供了更强大灵活的接口,且无需 jQuery 库。
示例: 使用 Fetch 发送 GET 请求:
fetch('https://api.example.com/users/1') .then(response => { if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return response.json(); // 将响应体解析为 JSON }) .then(data => { console.log('用户数据:', data); }) .catch(error => { console.error('Fetch 错误:', error); });考虑在新项目或尚未包含 jQuery 的项目中使用 Fetch API,但了解 jQuery 的 AJAX 方法对于维护现有代码库仍然有价值。
jQuery AJAX 参考
Section titled “jQuery AJAX 参考”要全面了解所有 jQuery AJAX 方法和选项,请查阅官方 jQuery AJAX 文档。