AJAX允许在不刷新整个页面的情况下与服务器交换数据并更新部分网页内容。本文将详细介绍 jQuery AJAX 的核心用法。
本文目录
-
-
-
- 1. 基础 AJAX 方法简单使用
- 2. $.ajax()
- 3. 处理异步请求的返回值
- 4. AJAX 请求前的预处理
- 5. 全局 AJAX 事件
- 6. 文件上传
- 7. 跨域请求
- 8. 取消 AJAX 请求
-
-
1. 基础 AJAX 方法简单使用
下面实现一下GET、POST等的使用
// GET 请求
$.get("data.php", { name: "9527", age: 30 }, function(data) {
$("#result").html(data);
});
// POST 请求
$.post("submit.php", { action: "login", user: "admin" }, function(response) {
alert("登录结果: " + response);
});
// 加载 HTML 内容到元素
$("#container").load("content.html", function() {
console.log("内容加载完成");
});
// 获取 JSON 数据
$.getJSON("data.json", function(data) {
$.each(data.items, function(index, item) {
$("ul").append("<li>" + item.name + "</li>");
});
});
2. $.ajax()
$.ajax() 是最底层的方法,支持所有 AJAX 选项
$.ajax({
url: "api/data", // 请求URL
method: "POST", // 请求方法 ,GET, POST, PUT, DELETE等
dataType: "json", // 预期的响应数据类型 (xml, json, script, html, text等)
data: { action: "fetch" }, // 发送到服务器的数据
contentType: "application/json", // 请求头的Content-Type
timeout: 3000, // 请求超时时间(毫秒)
success: function(response) { // 请求成功时的回调
console.log("成功:", response);
},
error: function(xhr, status, error) { // 请求失败时的回调
console.error("错误:", status, error);
},
complete: function() { // 请求完成时的回调(无论成功或失败)
console.log("请求完成");
}
});
3. 处理异步请求的返回值
AJAX 请求是异步的,不能直接返回值,但可以通过回调函数、Promise 或 Deferred 对象处理结果
// Promise 语法
$.ajax("data.json")
.done(function(data) {
// 请求成功
$("#result").html(data);
})
.fail(function(error) {
// 请求失败
console.error("AJAX 失败:", error);
})
.always(function() {
// 无论成功或失败都会执行
$("#loading").hide();
});
4. AJAX 请求前的预处理
可以使用 beforeSend 选项在请求发送前进行操作
$.ajax({
url: "upload.php",
method: "POST",
data: formData,
processData: false, // 不处理数据
contentType: false, // 不设置Content-Type
beforeSend: function(xhr) {
// 显示加载状态
$("#loading").show();
// 设置请求头
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
},
success: function(response) {
// 处理响应
},
complete: function() {
// 隐藏加载状态
$("#loading").hide();
}
});
5. 全局 AJAX 事件
jQuery 提供了全局 AJAX 事件,可用于监控页面中所有 AJAX 请求的状态
// 所有 AJAX 请求开始时执行
$(document).ajaxStart(function() {
$("#global-loader").show();
});
// 所有 AJAX 请求完成时执行
$(document).ajaxComplete(function() {
$("#global-loader").hide();
});
// 所有 AJAX 请求成功时执行
$(document).ajaxSuccess(function(event, xhr, settings) {
console.log("全局成功:", settings.url);
});
// 所有 AJAX 请求失败时执行
$(document).ajaxError(function(event, xhr, settings, error) {
console.error("全局错误:", settings.url, error);
});
6. 文件上传
使用 FormData 对象处理文件上传
<form id="uploadForm" enctype="multipart/form-data">
<input type="file" name="file" />
<button type="submit">上传</button>
</form>
$("#uploadForm").submit(function(e) {
e.preventDefault();
const formData = new FormData(this);
$.ajax({
url: "upload.php",
method: "POST",
data: formData,
contentType: false,
processData: false,
success: function(response) {
alert("上传成功: " + response);
}
});
});
7. 跨域请求
使用 JSONP 或 CORS 处理跨域请求
// JSONP 请求,适用于老旧浏览器
$.ajax({
url: "https://api.com/data",
dataType: "jsonp", // 指定为JSONP
jsonp: "callback", // 指定回调函数名参数
success: function(data) {
console.log("跨域数据:", data);
}
});
// CORS 请求,现代浏览器推荐
// 服务器需要设置响应头:Access-Control-Allow-Origin
$.ajax({
url: "https://api.com/data",
method: "GET",
crossDomain: true,
success: function(data) {
console.log("CORS 数据:", data);
}
});
8. 取消 AJAX 请求
可以使用 jqXHR 对象取消正在进行的请求
let xhr;
$("#fetchButton").click(function() {
// 取消之前的请求
if (xhr) xhr.abort();
xhr = $.ajax({
url: "large-data.json",
success: function(data) {
$("#result").html(data);
},
error: function(e) {
if (e.statusText === "abort") {
console.log("请求被取消");
}
}
});
});
$("#cancelButton").click(function() {
if (xhr) xhr.abort();
});
| ← 上一篇 AngularJS知识快速入门(上) |
记得点赞、关注、收藏哦! |
下一篇 Ajax——在OA系统提升性能的局部刷新 → |




