$.ajax() 基础方法
$.ajax()
是 jQuery 中最底层的 AJAX 实现,支持高度自定义配置:
javascript
$.ajax({
url: "https://api.example.com/data",
type: "GET", // 或 "POST"
dataType: "json", // 预期返回的数据类型
data: { key1: "value1", key2: "value2" }, // 发送的数据
success: function(response) {
console.log("请求成功:", response);
},
error: function(xhr, status, error) {
console.error("请求失败:", status, error);
}
});
快捷方法
jQuery 提供了更简洁的快捷方法:
GET 请求
javascript
$.get("https://api.example.com/data", { param1: "value1" }, function(response) {
console.log("GET 响应:", response);
}, "json");
POST 请求
javascript
$.post("https://api.example.com/submit", { name: "John", age: 30 }, function(response) {
console.log("POST 响应:", response);
});
加载 HTML 片段
javascript
$("#result").load("partial.html #content"); // 加载指定元素的片段
处理 JSON 数据
获取 JSON 数据
javascript
$.getJSON("https://api.example.com/users", function(data) {
$.each(data, function(index, user) {
console.log(user.name);
});
});
提交 JSON 数据
javascript
$.ajax({
url: "https://api.example.com/save",
type: "POST",
contentType: "application/json",
data: JSON.stringify({ id: 1, name: "Alice" }),
success: function(response) {
console.log("保存成功");
}
});
全局事件处理
jQuery 允许绑定全局 AJAX 事件:
javascript
$(document).ajaxStart(function() {
$("#loading").show();
}).ajaxStop(function() {
$("#loading").hide();
});
跨域请求 (CORS)
对于跨域请求,确保服务器支持 CORS:
javascript
$.ajax({
url: "https://other-domain.com/api",
crossDomain: true,
xhrFields: {
withCredentials: true // 需要时发送凭据
}
});
使用 Promises
jQuery AJAX 返回的是 jqXHR
对象,支持 Promise 语法:
javascript
$.get("https://api.example.com/data")
.done(function(data) {
console.log("成功:", data);
})
.fail(function(xhr, status) {
console.error("失败:", status);
});