jQuery AJAX 方法学习笔记

AJAX 简介

AJAX,全称为 Asynchronous JavaScript And XML,是一种用于创建快速动态网页的技术。通过使用 AJAX,你可以在不刷新整个页面的情况下更新部分页面,从而提高用户体验。

jQuery AJAX 方法

jQuery 提供了一组简单易用的 AJAX 方法,可以帮助你轻松实现 AJAX 功能。以下是常用的 jQuery AJAX 方法:

  • $.ajax():执行异步 AJAX 请求
  • $.get():向服务器发送 GET 请求
  • $.post():向服务器发送 POST 请求
  • $.getJSON():从服务器获取 JSON 格式数据

$.ajax() 方法

$.ajax() 方法用于执行异步 AJAX 请求,可以自定义请求的各种参数,例如:

javascriptCopy Code
$.ajax({ url: "example.php", // 请求地址 method: "POST", // 请求方式 data: { name: "John", age: 30 }, // 发送的数据 success: function(result) { // 成功回调函数 console.log(result); }, error: function(xhr, status, error) { // 失败回调函数 console.log(status); } });

$.get() 和 $.post() 方法

.get()方法用于向服务器发送GET请求,.get() 方法用于向服务器发送 GET 请求,.post() 方法用于向服务器发送 POST 请求。它们都可以简化 AJAX 请求的代码量,例如:

javascriptCopy Code
// 发送 GET 请求 $.get("example.php", function(result) { console.log(result); }); // 发送 POST 请求 $.post("example.php", { name: "John", age: 30 }, function(result) { console.log(result); });

$.getJSON() 方法

$.getJSON() 方法用于从服务器获取 JSON 格式数据,例如:

javascriptCopy Code
$.getJSON("example.json", function(result) { console.log(result); });

实例

以下是一个实例,演示如何使用 jQuery AJAX 方法向服务器发送 POST 请求,并将返回的数据显示在页面上:

htmlCopy Code
<!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function() { $("#submit").click(function() { $.post("example.php", { name: $("#name").val(), age: $("#age").val() }, function(result) { $("#result").html(result); }); }); }); </script> </head> <body> <form> Name: <input type="text" id="name"><br> Age: <input type="text" id="age"><br> <input type="button" id="submit" value="Submit"> </form> <div id="result"></div> </body> </html>

在上面的例子中,当用户点击 Submit 按钮时,页面会向 example.php 文件发送一个 POST 请求,并将输入框中的 name 和 age 参数传递给服务器。服务器返回的数据会显示在 id 为 result 的 div 元素中。