jQuery Ajax

这篇博客介绍了jQuery的AJAX功能,包括$.ajax()的基本使用、load()、get()和post()方法,以及getScript()和getJSON()。详细讲解了各种方法的参数和应用场景,还提到了表单序列化和AJAX事件的处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

jQuery中文开发文档

ajax简介

  • ajax:向服务器请求数据,异步加载到页面;在不重新加载整个页面的情况下,与服务器交换数据并更新网页一部分
  • 同步加载:每次请求,必定重新加载响应回来一整张页面

$.ajax()请求代码格式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jQuery的ajax</title>
    <script src="./jquery-3.4.1.min.js"></script>
    <style type="text/css">
        h1{margin: 0 auto; text-align: center;}
        #box{width: 500px; margin: 0 auto;}
        input{width: 400px; height: 40px;}
    </style>
    <script>
        $(function(){
            // 给按钮添加单击事件
            $("#sbt").click(function(){
                // $.ajax();接收一个对象如下

                $.ajax({
                    type:"POST",     //ajax请求使用post方法
                    url:"服务器地址", //请求的服务器地址
                    data:{           //发送到服务器的数据,使用json数据类型
                        "键1":"值1",
                        "键2":"值2",
                    },
                    dataType:"json", //指定从服务器返回json数据类型
                    success:function(参数){
                        //请求成功要执行的代码
                        // 参数:从服务器返回的数据
                    },
                    error:function(){
                        // 请求失败要执行的代码
                    }
                });
            });
        });
    </script>
</head>
<body>
    <h1>登录</h1>
    <div id="box">
        姓名:<input type="text" name="uname" id="uname" value="">
        <br><br>
        密码:<input type="password" name="password" id="password" value="">
        <br><br>
        <input type="submit" id="sbt" value="登录">
    </div>
</body>
</html>

发送请求并返回数据

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jQuery的ajax</title>
    <script src="./jquery-3.4.1.min.js"></script>
    <style type="text/css">
        h1{margin: 0 auto; text-align: center;}
        #box{width: 500px; margin: 0 auto;}
        input{width: 400px; height: 40px;}
    </style>
    <script>
        $(function(){
            // 给按钮添加单击事件
            $("#sbt").click(function(){
                // $.ajax();接收一个对象如下

                $.ajax({
                    type:"POST",     //ajax请求使用post方法
                    url:"http://127.0.0.1/ajax/index.php", //请求的服务器地址
                    data:{           //发送到服务器的数据,使用json数据类型
                        "uname": $("#uname").val(),
                        "password":$("#password").val(),
                    },
                    dataType:"json", //指定从服务器返回json数据类型
                    success:function(dat){
                        //请求成功要执行的代码
                        // 参数:从服务器返回的数据
                        console.log(dat)
                    },
                    error:function(){
                        // 请求失败要执行的代码
                        alert("请求失败");
                    }
                });
            });
        });
    </script>
</head>
<body>
    <h1>登录</h1>
    <div id="box">
        姓名:<input type="text" name="uname" id="uname" value="">
        <br><br>
        密码:<input type="password" name="password" id="password" value="">
        <br><br>
        <input type="submit" id="sbt" value="登录">
    </div>
</body>
</html>
<?php
    // 处理跨域报错
    header("Access-Control-Allow-Origin: *");
    $uname = $_POST["uname"];
    $pwd = $_POST["password"];

    // 转成json数据类型
    echo json_encode([$uname, $pwd]);
?>

数据验证并加载到页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jQuery的ajax</title>
    <script src="./jquery-3.4.1.min.js"></script>
    <style type="text/css">
        h1{margin: 0 auto; text-align: center;}
        #box{width: 500px; margin: 0 auto;}
        input{width: 400px; height: 40px;}
        #box2{
            width: 500px; margin: 50px auto; display: none;
        }
        #box2 span{color: red; font-weight: 700;}
    </style>
    <script>
        $(function(){
            // 给按钮添加单击事件
            $("#sbt").click(function(){
                // $.ajax();接收一个对象如下

                $.ajax({
                    type:"POST",     //ajax请求使用post方法
                    url:"http://127.0.0.1/ajax/index.php", //请求的服务器地址
                    data:{           //发送到服务器的数据,使用json数据类型
                        "uname": $("#uname").val(),
                        "password":$("#password").val(),
                    },
                    dataType:"json", //指定从服务器返回json数据类型
                    success:function(dat){
                        //请求成功要执行的代码
                        // 参数:从服务器返回的数据
                        console.log(dat);
                        $("#box2").show().siblings("#box").hide();
                        $("#box2 span:eq(0)").text(dat.uname).siblings("span").text(dat.money);
                    },
                    error:function(){
                        // 请求失败要执行的代码
                        alert("请求失败");
                    }
                });
            });
        });
    </script>
</head>
<body>
    <h1>登录</h1>
    <div id="box">
        姓名:<input type="text" name="uname" id="uname" value="">
        <br><br>
        密码:<input type="password" name="password" id="password" value="">
        <br><br>
        <input type="submit" id="sbt" value="登录">
    </div>

    <div id="box2">
        欢迎:<span></span>会员<br>
        您有:<span></span>金币
    </div>
</body>
</html>
<?php
    // 处理跨域报错
    header("Access-Control-Allow-Origin: *");
    $uname = $_POST["uname"];
    $pwd = $_POST["password"];

    //根据$uname到数据库中查询相关的数据
    $hy = array("uname"=>"OliGit", "pwd"=>"123456", "money"=>"50000");

    // 数据验证
    if($pwd == $hy["pwd"]){
        echo json_encode($hy);
    }
    // 转成json数据类型
    // echo json_encode([$uname, $pwd]);
?>

load()方法

jQuery load()方法作用是从服务器加载数据,是一个简单但强大的AJAX方法

  • load(url, data, function(response, status, xhr)):从服务器加载数据并且将返回的 HTML 代码插入至匹配的元素中

参数说明

1、url:一个包含发送请求的URL字符串
2、data:向服务器发送请求的key:value参数,例如{name:“OliGit”}
3、function():当请求成功后执行的回调函数
(1)、responseTxt:包含调用成功时的结果内容
(2)、statusTxt:包含调用的状态:可能是“success”、“notmodified”、“error”、“timeout”、“abort”或“parsererror”中的一个,最常见的是:success成功;error错误
(3)、xhr:经过jQuery封装的XMLHttpRequest对象(保留其本身的所有属性和方法)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>load</title>
    <script src="./jquery-3.4.1/jquery-3.4.1.min.js"></script>
</head>
<body>
    <input type="button" value="ajax测试" id="btn">
    <div id="div1"></div>
    <script>
        $(function(){
            $("#btn").click(function(){
                // $("#div1").load("test.html .p2");
                // get提交
                // $("#div1").load("test.php?password=123456");
                // post提交
                // $("#div1").load("test.php", {
                //     password:"123456"
                // })

                // 回调函数
                $("#div1").load("test.php", {
                    password:"123456"
                }, function(responseTxt, statusTxt, xhr){
                    // alert(responseTxt);
                    // $('#div1').html(responseTxt + "谢谢访问");

                    // alert(statusTxt);//success
                    // if(statusTxt == "success"){
                    //     alert("数据加载成功")
                    // }else{
                    //     alert("数据加载失败")
                    // }

                    alert(xhr.responseText);//登录成功
                    alert(xhr.statusText);//OK
                    alert(xhr.status);//200
                })
            })
        })
    </script>
</body>
</html>

get()和post()方法

两种在客户端和服务端进行请求-响应的常用方法是:GET和POST
GET基本上用于从服务器获得(取回)数据。(GET方法可能返回缓存数据)
POST也可用于从服务器获取数据。(POST方法不会缓存数据,并且常用于连同请求一起发送数据)

$.get(URL, data, callback)

  • URL:一个包含发送请求的URL字符串
  • data:可选,发送给服务器的字符串或Key/value键值对
  • callback:当请求成功后执行的回调函数

$.post(URL, data, callback)

  • URL:一个包含发送请求的URL字符串
  • data:可选,发送给服务器的字符串或Key/value键值对
  • callback:当请求成功后执行的回调函数
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>get和post方法</title>
    <script src="./jquery-3.4.1/jquery-3.4.1.min.js"></script>
</head>
<body>
    <input type="button" id="btn" value="Ajax测试">
    <div id="text"></div>
    <script>
        $(function(){
            $("#btn").click(function(){
                 //get方式提交数据1
                // $.get("./test.html", function(data, statusTxt){
                //     alert(data);
                //     alert(statusTxt);
                // });

                 //get方式提交数据2
                //  $.get("./testGET.php?password=123456", function(responseTxt, statusTxt){
                //     // alert(responseTxt);
                //     // alert(statusTxt);
                //     $("#text").html(responseTxt);
                // });

                //get方式提交数据4
                // $.get("./testGET.php", {password : "123456"}, function(responseTxt, statusTxt){
                //     $("#text").html(responseTxt);
                // });

                //get方式提交数据4
                // $.get("./testGET.php", {password : "123456"}, function(responseTxt, statusTxt){
                //     $("#text").html(responseTxt);
                // });
// ===============================================================================================
                //post方式提交数据1
                // $.post("./testPOST.php", {password : "123456"}, function(responseTxt, statusTxt){
                //     $("#text").html(responseTxt);
                // });
                
                //post方式提交数据2
                $.post("./testPOST.php", "password=123456", function(responseTxt, statusTxt){
                    $("#text").html(responseTxt);
                });
            })
        })
    </script>
</body>
</html>

getScript()和getJSON()方法

getScript()和getJSON()方法专门用来加载JS/JSON文件

getScript

通过HTTP GET 请求从服务器加载并执行JavaScript文件

语法:$.getScript(url, function(response, statusTxt))

  • url:一个包含发送请求的URL字符串
  • response:包含来自请求的结果数据
  • statusTxt:包含请求的状态(success、error、notmodified,timeout,parsererror)

getJSON

通过HTTP GET 请求从服务器加载JSON文件

语法:$.getJSON(url, data,function(response, statusTxt, xhr))

  • url:一个包含发送请求的URL字符串
  • data:发送给服务器的字符串或Key/value键值对
  • function:当请求成功后执行的回调函数
  • response:包含来自请求的结果数据
  • statusTxt:包含请求的状态(success、error、notmodified,timeout,parsererror)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>getScript和getJSON方法</title>
    <script src="./jquery-3.4.1/jquery-3.4.1.min.js"></script>
</head>
<body>
    <input type="button" id="btn" value="Ajax测试">
    <div id="text"></div>
    <script>
        $(function(){
            // getScript加载并执行
            // $("#btn").click(function(){
            //      $.getScript("test.js");
            // })

            // $("#btn").click(function(){
            //      $.getScript("test.js", function(response, statusTxt){
            //          alert("js文件加载成功");
            //          alert(response);
            //          alert(statusTxt);
            //      });
            // })

            // getJSON
            $("#btn").click(function(){
                 $.getJSON("test.json", function(response, statusTxt){
                    //  alert(response);
                    //  alert(statusTxt);
                    alert(response[0].name);
                 });
            })
        })
    </script>
</body>
</html>

ajax方法

ajax()方法是jQuery底层AJAX实现。之前的get和post等视为高层实现。Ajax返回其创建的XMLHttpRequest对象。

语法:$.ajax([setting])
setting:可选;用于配置Ajax请求的键值对集合
url:默认值,当前页面地址。发送请求的地址
type:请求方式(get或post),默认为get
success:请求成功后的回调函数
error:请求失败时调用此函数

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax方法</title>
    <script src="./jquery-3.4.1/jquery-3.4.1.min.js"></script>
</head>
<body>
    <input type="button" id="btn" value="Ajax测试">
    <div id="text"></div>
    <script>
        $(function(){
            $("#btn").click(function(){
                $.ajax({
                    url : "testPOST.php",
                    type : "post",
                    data : {password:"123456"},
                    success : function(responseTxt, statusTxt, xhr){
                        alert(responseTxt)
                    },
                    error : function(){
                        alert("加载失败");
                    }
                })
            })
        })
    </script>
</body>
</html>

表单序列化

语法:$(selector).serialize()

jQuery的serialize()方法通过序列化表单值,创建URL编码文本字符串,这样,我们就可以把序列化的值传给Ajax()作为URL的参数,轻松使用Ajax()提交form表单了,而不需要一个一个获取表单的值然后传给Ajax()

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>serialize</title>
    <script src="./jquery-3.4.1/jquery-3.4.1.min.js"></script>
</head>
<body>
    <form action="#" id="form1">
        姓名: <input type="text" name="user"><br>
        电话: <input type="text" name="tel"><br>
        <select name="buy">
            <option>买新房</option>
            <option>买新车</option>
        </select>
        <input type="button" value="提交">
    </form>
    <div></div>
    <script>
        $(function(){
            $("form input[type=button]").click(function(){
               $.ajax({
                   type : "POST",
                   url : "./buy.php",
                //    方式1
                //    data : {
                //     user : $("form input[name=user]").val(),
                //     tel : $("form input[name=tel]").val(),
                //     buy : $("form select[name=buy]").val(),
                //    },

                // 方式2
                    data : $("form").serialize(),
                   success : function(responseTxt, statusTxt, xhr){
                    //    alert(responseTxt);
                        $("div").html(responseTxt);
                   }
               })
            })
        })
    </script>
</body>
</html>
<?php
    echo $_POST['buy'].'----'.$_POST['user'].'----'.$_POST['tel']
?>

serializeArray():序列化表单元素(类似“.serialize()”方法),返回JSON数据结构对象

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>serializeArray</title>
    <script src="./jquery-3.4.1/jquery-3.4.1.min.js"></script>
</head>
<body>
    <form action="#" id="form1">
        姓名: <input type="text" name="user"><br>
        电话: <input type="text" name="tel"><br>
        <select name="buy">
            <option>买新房</option>
            <option>买新车</option>
        </select>
        <input type="button" value="提交">
    </form>
    <div></div>
    <script>
        $(function(){
            $("form input[type=button]").click(function(){
               $.ajax({
                   type : "POST",
                   url : "./buy.php",
                   data : $("form").serializeArray(),
                   success : function(responseTxt, statusTxt, xhr){
                        // $("div").html(responseTxt);
                        var obj = $("form").serializeArray();
                        alert(obj[0].name);
                        // $("div").html(obj);//不能放到HTML中
                        // console.log(obj);
                        // [{name: "user", value: "13"},
                        // {name: "tel", value: "23415345"},
                        // {name: "buy", value: "买新房"}]
                   }
               })
            })
        })
    </script>
</body>
</html>

ajax 事件

  • ajaxStart():AJAX请求开始时执行函数
  • ajaxSend():AJAX请求发送前执行函数
  • ajaxComplete():AJAX请求完成时执行函数
  • ajaxSuccess():AJAX请求成功时执行函数
  • ajaxError():AJAX请求错误时执行函数
  • ajaxStop():AJAX请求结束时执行函数
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax事件</title>
    <script src="jquery-3.4.1/jquery-3.4.1.min.js"></script>
</head>
<body>
    <input type="button" id="btn" value="ajax事件">
    <div id="test"></div>
    <script>
        $(function(){
            $("#btn").click(function(){
                $("#test").load("phpString.php");
            })

            $(document).ajaxStart(function(){
                alert("ajaxStart():AJAX请求开始时执行函数");
            })
            $(document).ajaxSend(function(){
                alert("ajaxSend():AJAX请求发送前执行函数");
            })
            $(document).ajaxComplete(function(){
                alert("ajaxComplete():AJAX请求完成时执行函数");
            })
            $(document).ajaxSuccess(function(){
                alert("ajaxSuccess():AJAX请求成功时执行函数");
            })
            $(document).ajaxError(function(){
                alert("ajaxError():AJAX请求错误时执行函数");
            })
            $(document).ajaxStop(function(){
                alert("ajaxStop():AJAX请求结束时执行函数");
            })
        })
    </script>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值