加载中...
load()方法是最简单的动态加载方法,可以从服务器加载数据并放入匹配的元素中。
// 基本用法 - 加载整个文件
$("#loadBtn").click(function(){
$("#result").load("content.html");
});
// 加载文件的部分内容(使用选择器)
$("#loadPartialBtn").click(function(){
$("#result").load("content.html #specific-section");
});
// 带回调函数
$("#loadCallbackBtn").click(function(){
$("#result").load("data.php", function(response, status, xhr){
if(status == "success") {
console.log("加载成功!");
console.log("响应内容:", response);
} else {
console.log("加载失败");
}
});
});
// 带参数的加载
$("#loadWithDataBtn").click(function(){
$("#result").load("data.php", {
user_id: 123,
action: "get_profile"
});
});
// 加载失败处理
$("#loadErrorBtn").click(function(){
$("#result").load("nonexistent.html", function(response, status, xhr){
if(status == "error") {
$("#result").html("加载失败: " + xhr.status + " " + xhr.statusText);
}
});
});
jQuery提供了完整的AJAX方法,可以更精细地控制HTTP请求。
// $.get() 方法 - GET请求
$("#getBtn").click(function(){
$.get("api/data.php", { id: 123 }, function(data){
$("#result").html(data);
});
});
// $.post() 方法 - POST请求
$("#postBtn").click(function(){
$.post("api/save.php", {
name: $("#name").val(),
email: $("#email").val()
}, function(response){
console.log("保存成功:", response);
});
});
// $.ajax() 方法 - 完整控制
$("#ajaxBtn").click(function(){
$.ajax({
url: "api/data.php",
type: "GET",
dataType: "json",
data: { user_id: 123 },
beforeSend: function(){
$("#loading").show();
},
success: function(response){
$("#result").html(JSON.stringify(response));
},
error: function(xhr, status, error){
console.log("请求失败:", status, error);
},
complete: function(){
$("#loading").hide();
}
});
});
// 并发请求
$("#multipleBtn").click(function(){
$.when(
$.get("api/user.php"),
$.get("api/products.php")
).then(function(userResp, productResp){
var user = userResp[0];
var products = productResp[0];
// 处理两个请求的结果
});
});
// 设置全局AJAX默认值
$.ajaxSetup({
timeout: 5000, // 5秒超时
cache: false // 禁用缓存
});
JSON是现代Web应用中最常用的数据格式,jQuery提供了方便的方法处理JSON数据。
// $.getJSON() 方法 - 获取JSON数据
$("#getJSONBtn").click(function(){
$.getJSON("api/users.json", function(data){
var html = "<ul>";
$.each(data, function(index, user){
html += "<li>" + user.name + " - " + user.email + "</li>";
});
html += "</ul>";
$("#result").html(html);
});
});
// 解析JSON字符串
var jsonString = '{"name":"张三","age":25,"city":"北京"}';
var jsonObj = JSON.parse(jsonString);
console.log(jsonObj.name); // 输出:张三
// 创建JSON字符串
var user = {
name: "李四",
age: 30,
hobbies: ["阅读", "游泳", "编程"]
};
var jsonStr = JSON.stringify(user);
// 处理嵌套JSON
$.getJSON("api/complex.json", function(data){
// 访问嵌套属性
var userName = data.user.profile.name;
var userPosts = data.posts;
// 使用模板构建HTML
var template = "<div class='user-profile'>" +
"<h3>{{name}}</h3>" +
"<p>邮箱: {{email}}</p>" +
"</div>";
var html = template
.replace("{{name}}", data.user.name)
.replace("{{email}}", data.user.email);
$("#profile").html(html);
});
// 错误处理
$.getJSON("api/data.json")
.done(function(data){
console.log("成功:", data);
})
.fail(function(jqxhr, textStatus, error){
console.log("失败:", textStatus, error);
});
{
"success": true,
"message": "数据获取成功",
"data": {
"users": [
{
"id": 1,
"name": "张三",
"email": "zhangsan@example.com",
"age": 25
},
{
"id": 2,
"name": "李四",
"email": "lisi@example.com",
"age": 30
}
],
"total": 2
}
}
使用AJAX提交表单,实现无刷新表单处理,提升用户体验。
// 表单序列化提交
$("#myForm").submit(function(e){
e.preventDefault(); // 阻止默认表单提交
var formData = $(this).serialize(); // 序列化表单数据
$.post("api/submit.php", formData, function(response){
if(response.success){
$("#result").html("<div class='alert alert-success'>" +
response.message + "</div>");
} else {
$("#result").html("<div class='alert alert-danger'>" +
response.message + "</div>");
}
}, "json");
});
// 表单序列化数组
$("#formArrayBtn").click(function(){
var formArray = $("#myForm").serializeArray();
console.log(formArray); // 输出:[{name: 'field1', value: 'value1'}, ...]
// 转换为对象
var formObject = {};
$.each(formArray, function(i, field){
formObject[field.name] = field.value;
});
});
// 表单数据验证
$("#validateForm").submit(function(e){
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
var errors = [];
if(name.length < 2){
errors.push("姓名至少2个字符");
}
if(!email.match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/)){
errors.push("邮箱格式不正确");
}
if(errors.length > 0){
$("#errors").html("<div class='alert alert-danger'><ul>" +
errors.map(function(e){ return "<li>" + e + "</li>"; }).join('') +
"</ul></div>");
return false;
}
// 验证通过,提交表单
submitForm();
});
// 文件上传(需要FormData)
$("#fileForm").submit(function(e){
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: "api/upload.php",
type: "POST",
data: formData,
processData: false, // 重要:告诉jQuery不要处理数据
contentType: false, // 重要:不要设置内容类型
success: function(response){
console.log("上传成功:", response);
},
error: function(xhr, status, error){
console.log("上传失败:", error);
}
});
});
创建一个简单的用户评论系统,包含动态加载评论和提交新评论功能。
| 方法 | 描述 | 适用场景 | 特点 |
|---|---|---|---|
.load() |
加载HTML内容到元素 | 简单的HTML片段加载 | 简单易用,自动插入DOM |
$.get() |
发送GET请求 | 获取数据,不修改服务器状态 | 简单快捷,适合获取数据 |
$.post() |
发送POST请求 | 提交数据,修改服务器状态 | 适合表单提交和数据保存 |
$.getJSON() |
获取并解析JSON数据 | API接口调用,获取结构化数据 | 自动解析JSON,返回JavaScript对象 |
$.ajax() |
完整的AJAX请求 | 需要精细控制的复杂请求 | 功能最全,可配置性强 |
$.ajaxSetup() |
设置全局AJAX默认值 | 统一设置请求参数 | 适合项目级别的配置 |