jQueryAJAX 方法

AJAX (Asynchronous JavaScript and XML) 允许网页在不重新加载的情况下与服务器交换数据并更新部分网页内容。

1. AJAX简介

AJAX 是一种创建快速动态网页的技术,通过在后台与服务器进行少量数据交换,实现网页的异步更新。

传统请求 vs AJAX请求
传统请求
  • 同步请求
  • 整个页面重新加载
  • 用户体验差
  • 带宽浪费
AJAX请求
  • 异步请求
  • 局部页面更新
  • 用户体验好
  • 节省带宽

基本工作原理:

AJAX工作原理

浏览器 → 发送AJAX请求 → 服务器 → 返回数据 → 更新页面局部

2. load() 方法

load() 方法从服务器加载数据,并把返回的数据放入被选元素中。

内容加载区域...
模拟从服务器加载数据

代码示例:


// 基本用法 - 加载整个文件
$("#loadBtn").click(function(){
    $("#content").load("demo_test.html");
});

// 加载文件中的特定元素
$("#loadPartBtn").click(function(){
    // 只加载demo_test.html中id为content的元素
    $("#content").load("demo_test.html #content");
});

// 带回调函数
$("#content").load("demo_test.html", function(response, status, xhr){
    if(status == "success"){
        console.log("数据加载成功!");
        console.log("响应内容:", response);
    }
    if(status == "error"){
        console.log("错误: " + xhr.status + " " + xhr.statusText);
    }
});

// 发送数据到服务器
$("#content").load("test.php", {
    name: "张三",
    age: 25
});

// 加载完成后执行操作
$("#content").load("data.txt", function(){
    $(this).addClass("loaded");
    $(this).fadeIn("slow");
});
                            
注意:由于浏览器的安全限制,load() 方法可能无法跨域加载数据,除非目标服务器允许CORS。

3. $.get() 方法

$.get() 方法通过 HTTP GET 请求从服务器加载数据。

请求结果将显示在这里...
请求状态:
等待请求...

代码示例:


// 基本用法
$.get("demo_test.php", function(data, status){
    console.log("数据: " + data + "\n状态: " + status);
});

// 获取JSON数据
$.get("users.json", function(data){
    // data已经是JavaScript对象
    $.each(data, function(index, user){
        $("#userList").append("
  • " + user.name + "
  • "); }); }); // 带参数的GET请求 $.get("search.php", { keyword: "jquery", page: 1, limit: 10 }, function(data){ $("#results").html(data); }); // 指定数据类型 $.get("data.php", function(data){ // 处理数据 }, "json"); // 指定返回类型为JSON // 使用Promise风格的调用 $.get("api/data") .done(function(data) { console.log("请求成功", data); }) .fail(function(jqXHR, textStatus, errorThrown) { console.log("请求失败", textStatus); }) .always(function() { console.log("请求完成"); });

    实际API调用示例:

    
    // 使用公共API获取数据
    $("#getUsers").click(function(){
        $.get("https://jsonplaceholder.typicode.com/users", function(users){
            let output = "
    用户列表
      "; $.each(users, function(i, user){ output += `
    • ${user.name} (${user.email})
    • `; }); output += "
    "; $("#userList").html(output); }); }); // 获取特定用户 $("#getUser").click(function(){ const userId = $("#userId").val(); $.get(`https://jsonplaceholder.typicode.com/users/${userId}`, function(user){ $("#userInfo").html(`
    用户详情

    姓名: ${user.name}

    邮箱: ${user.email}

    电话: ${user.phone}

    `); }); });

    4. $.post() 方法

    $.post() 方法通过 HTTP POST 请求向服务器提交数据。

    提交表单数据:
    响应结果:
    提交结果将显示在这里...

    代码示例:

    
    // 基本用法
    $.post("submit.php", {
        name: "张三",
        age: 25
    }, function(data, status){
        console.log("返回数据: " + data);
        console.log("状态: " + status);
    });
    
    // 提交表单数据
    $("#submitBtn").click(function(){
        const formData = {
            username: $("#username").val(),
            email: $("#email").val(),
            message: $("#message").val()
        };
    
        $.post("contact.php", formData, function(response){
            if(response.success){
                $("#result").html("
    提交成功!
    "); } else { $("#result").html("
    提交失败:" + response.error + "
    "); } }, "json"); // 期望返回JSON格式 }); // 使用FormData对象(支持文件上传) $("#uploadForm").submit(function(e){ e.preventDefault(); const formData = new FormData(this); $.post({ url: "upload.php", data: formData, processData: false, // 告诉jQuery不要处理数据 contentType: false, // 告诉jQuery不要设置Content-Type success: function(response){ console.log("上传成功", response); } }); }); // 注册用户示例 $("#registerBtn").click(function(){ const userData = { username: $("#username").val(), password: $("#password").val(), email: $("#email").val() }; $.post("/api/register", userData) .done(function(data){ alert("注册成功!"); window.location.href = "/dashboard"; }) .fail(function(xhr){ alert("注册失败: " + xhr.responseText); }); });

    模拟RESTful API调用:

    
    // 创建新文章
    $("#createPost").click(function(){
        const postData = {
            title: $("#title").val(),
            body: $("#content").val(),
            userId: 1
        };
    
        $.post("https://jsonplaceholder.typicode.com/posts", postData)
            .done(function(data){
                console.log("创建成功,ID:", data.id);
                $("#result").html(`文章创建成功!ID: ${data.id}`);
            });
    });
    
    // 更新文章(使用PUT,但这里用POST模拟)
    $("#updatePost").click(function(){
        const postId = $("#postId").val();
        const postData = {
            title: $("#title").val(),
            body: $("#content").val()
        };
    
        $.post(`https://jsonplaceholder.typicode.com/posts/${postId}`, postData)
            .done(function(data){
                console.log("更新成功");
            });
    });
                                

    5. $.ajax() 方法

    $.ajax() 是jQuery中最底层、最强大的AJAX方法,可以完全控制AJAX请求。

    响应将显示在这里...
    请求详情:

    状态:未发送

    状态码:-

    响应时间:-

    数据大小:-

    代码示例:

    
    // 基本配置
    $.ajax({
        url: "test.php",        // 请求地址
        type: "GET",            // 请求方法 (GET, POST, PUT, DELETE)
        dataType: "json",       // 预期返回的数据类型
        data: {                 // 发送到服务器的数据
            name: "John",
            location: "Boston"
        },
        success: function(data, textStatus, jqXHR){
            // 请求成功时的处理
            console.log("成功:", data);
        },
        error: function(jqXHR, textStatus, errorThrown){
            // 请求失败时的处理
            console.log("错误:", textStatus, errorThrown);
        },
        complete: function(jqXHR, textStatus){
            // 请求完成时的处理(无论成功失败都会执行)
            console.log("请求完成");
        }
    });
    
    // 更多配置选项
    $.ajax({
        url: "api/data",
        method: "POST",         // method是type的别名
        timeout: 5000,          // 超时时间(毫秒)
        headers: {              // 自定义请求头
            "X-Requested-With": "XMLHttpRequest",
            "Authorization": "Bearer " + token
        },
        beforeSend: function(xhr){
            // 发送请求前的处理
            console.log("正在发送请求...");
            // 可以在这里添加loading效果
            $("#loading").show();
        },
        success: function(data){
            console.log("请求成功", data);
        },
        error: function(xhr, status, error){
            console.log("请求失败", status, error);
        },
        complete: function(){
            // 请求完成后隐藏loading
            $("#loading").hide();
        }
    });
    
    // 使用Promise
    $.ajax({
        url: "api/users",
        dataType: "json"
    })
    .then(function(data){
        console.log("成功", data);
        return $.ajax({
            url: `api/posts?userId=${data[0].id}`,
            dataType: "json"
        });
    })
    .then(function(posts){
        console.log("用户帖子", posts);
    })
    .catch(function(error){
        console.log("错误", error);
    });
                                

    完整的CRUD操作示例:

    
    // 1. 获取所有数据 (GET)
    function getAllUsers(){
        return $.ajax({
            url: "/api/users",
            method: "GET",
            dataType: "json"
        });
    }
    
    // 2. 获取单个数据 (GET)
    function getUser(id){
        return $.ajax({
            url: `/api/users/${id}`,
            method: "GET",
            dataType: "json"
        });
    }
    
    // 3. 创建数据 (POST)
    function createUser(userData){
        return $.ajax({
            url: "/api/users",
            method: "POST",
            contentType: "application/json",
            data: JSON.stringify(userData),
            dataType: "json"
        });
    }
    
    // 4. 更新数据 (PUT)
    function updateUser(id, userData){
        return $.ajax({
            url: `/api/users/${id}`,
            method: "PUT",
            contentType: "application/json",
            data: JSON.stringify(userData),
            dataType: "json"
        });
    }
    
    // 5. 删除数据 (DELETE)
    function deleteUser(id){
        return $.ajax({
            url: `/api/users/${id}`,
            method: "DELETE"
        });
    }
    
    // 使用示例
    $("#loadUsers").click(function(){
        getAllUsers()
            .done(function(users){
                renderUserList(users);
            })
            .fail(function(error){
                showError("加载用户失败: " + error.statusText);
            });
    });
    
    $("#saveUser").click(function(){
        const userData = {
            name: $("#name").val(),
            email: $("#email").val(),
            phone: $("#phone").val()
        };
    
        createUser(userData)
            .done(function(newUser){
                alert(`用户创建成功,ID: ${newUser.id}`);
                $("#userForm")[0].reset();
            });
    });
                                
    提示: $.get()$.post() 都是 $.ajax() 的简写方法。例如 $.get(url, data, success, dataType) 等价于 $.ajax({url: url, type: 'GET', ...})

    6. JSON数据处理

    JSON(JavaScript Object Notation)是现代Web开发中最常用的数据交换格式。

    解析JSON数据:

    
    // 从服务器获取JSON数据
    $.getJSON("data.json", function(data){
        // data已经是JavaScript对象
        console.log("用户数量:", data.users.length);
    
        // 遍历数组
        $.each(data.users, function(index, user){
            console.log(`用户${index + 1}: ${user.name}`);
        });
    });
    
    // 使用$.ajax获取JSON
    $.ajax({
        url: "api/data",
        dataType: "json",
        success: function(data){
            // 处理嵌套的JSON数据
            if(data.status === "success"){
                renderData(data.results);
            }
        }
    });
    
    // 解析JSON字符串
    const jsonString = '{"name":"John","age":30,"city":"New York"}';
    const obj = JSON.parse(jsonString);
    console.log(obj.name); // 输出: John
    
    // 将对象转换为JSON字符串
    const user = {name: "Jane", age: 25};
    const jsonStr = JSON.stringify(user);
    console.log(jsonStr); // 输出: {"name":"Jane","age":25}
                                        

    处理复杂JSON结构:

    
    // 处理复杂JSON响应
    $.getJSON("https://jsonplaceholder.typicode.com/posts", function(posts){
        let output = "
    "; $.each(posts.slice(0, 5), function(i, post){ output += `
    ${post.title}

    ${post.body.substring(0, 100)}...

    `; }); output += "
    "; $("#postsContainer").html(output); }); // 获取嵌套数据 $("#postsContainer").on("click", ".view-comments", function(){ const postId = $(this).data("post-id"); $.getJSON(`https://jsonplaceholder.typicode.com/posts/${postId}/comments`, function(comments){ let commentList = "
      "; $.each(comments, function(i, comment){ commentList += `
    • ${comment.name}
      ${comment.email}
      ${comment.body}
    • `; }); commentList += "
    "; $("#commentsModal .modal-body").html(commentList); $("#commentsModal").modal("show"); }); });

    处理AJAX错误:

    
    // 全局错误处理
    $(document).ajaxError(function(event, jqXHR, ajaxSettings, thrownError){
        console.log("AJAX请求发生错误:");
        console.log("URL:", ajaxSettings.url);
        console.log("状态码:", jqXHR.status);
        console.log("错误信息:", thrownError);
    
        // 显示用户友好的错误信息
        let errorMsg = "请求失败,请稍后重试";
        if(jqXHR.status === 0){
            errorMsg = "网络连接失败,请检查网络设置";
        } else if(jqXHR.status === 404){
            errorMsg = "请求的资源不存在";
        } else if(jqXHR.status === 500){
            errorMsg = "服务器内部错误";
        }
    
        $("#errorMessage").html(`
    ${errorMsg}
    `); }); // 单个请求的错误处理 $.ajax({ url: "api/data", dataType: "json", success: function(data){ // 成功处理 }, error: function(jqXHR, textStatus, errorThrown){ // 特定错误处理 switch(jqXHR.status){ case 401: // 未授权,跳转到登录页 window.location.href = "/login"; break; case 403: alert("您没有权限执行此操作"); break; case 422: // 验证错误,显示具体错误信息 const errors = jqXHR.responseJSON.errors; displayValidationErrors(errors); break; default: alert("发生错误: " + textStatus); } } });

    jQuery AJAX方法速查表

    方法 描述 常用参数
    $.ajax() 执行异步HTTP (AJAX) 请求 url, type, data, success, error
    $.get() 使用GET请求加载数据 url, data, success, dataType
    $.post() 使用POST请求加载数据 url, data, success, dataType
    $.getJSON() 使用GET请求加载JSON数据 url, data, success
    .load() 加载HTML并插入到元素中 url, data, complete
    $.ajaxSetup() 设置全局AJAX默认选项 {}

    实战练习:创建天气查询应用

    使用AJAX调用天气API,创建一个简单的天气查询应用:

    天气信息
    点击查询按钮获取天气信息...
    注:这里使用模拟数据演示AJAX请求