336 jQuery中方法:ajax(),其他api,接口化开发,serialize

jQuery为我们提供了更强大的Ajax封装

$.ajax

参数列表

参数名称 描述 取值 示例
url 接口地址 url:"02.php"
type 请求方式 get/post type:"get"
timeout 超时时间 单位毫秒 timeout:5000
dataType 服务器返回的格式 json/xml/text(默认) dataType:"json"
data 发送的请求数据 对象 data:{name:"zs", age:18}
beforeSend 调用前的回调函数 function(){} beforeSend:function(){ alert(1) }
success 成功的回调函数 function (data) {} success:function (data) {}
error 失败的回调函数 function (error) {} error:function(data) {}
complete 完成后的回调函数 function () {} complete:function () {}

其他api(了解)

$.post(url, callback, [dataType]);只发送post请求
$.get(url, callback, [dataType]);
$.getJSON(url, callback);
$.getScript(url,callback);//载入服务器端的js文件
$("div").load(url);//载入一个服务器端的html页面。

使用示例

$.ajax({
  type:"get",//请求类型
  url:"02.php",//请求地址
  data:{name:"zs", age:18},//请求数据
  dataType:"json",//希望接受的数据类型
  timeout:5000,//设置超时时间
  beforeSend:function () {
    //alert("发送前调用");
  },
  success:function (data) {
    //alert("成功时调用");
    console.log(data);
  },
  error:function (error) {
    //alert("失败时调用");
    console.log(error);
  },
  complete:function () {
    //alert("请求完成时调用");
  }
});

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>jq-ajax的详细语法格式</title>
</head>

<body>
    <button>发送请求</button>
    <script src="../jquery-1.12.4.min.js"></script>
    <script>
        // jq-ajax的详细语法格式
        $('button').click(function() {
            $.ajax({
                type: 'get', // 请求方式
                url: './jqAajx.php', // 请求地址
                // 传递的数据,内部进行转换 name=zs&age=18
                data: {
                    name: 'zs'
                },
                // 超时时间,等待服务器响应时间,超过指定时间,自动终止请求
                // timeout: 2000, 
                //数据类型,告诉$.ajax返回的数据 以哪种类型进行处理【返回哪种数据类型】, 'text'【字符串】, 'json', 'xml', 'script'【少用】
                // 如果设置了dataType: 'json', 插件内部会自动将json数组转成js对象或者数组
                dataType: 'json',
                beforeSend: function() {
                    // 请求发送之前
                    // alert(1);
                    // 在请求发前,做一些准备工作,判断数据是否合理
                },
                success: function(info) {
                    //服务器成功响应回调函数
                    console.log(info); //用于渲染    
                    // alert(2);                
                },
                error: function() {
                    //请求出错的回调函数
                    // alert(3);
                    console.log('请求出错了');
                },
                complete: function() {
                    // 请求完成的回调函数
                    // 做一些收尾工作,样式重置
                    // alert(4);
                }
            })
        });
    </script>
</body>

</html>

接口化开发

请求地址即所谓的接口,通常我们所说的接口化开发,其实是指一个接口对应一个功能, 并且严格约束了请求参数响应结果 的格式,这样前后端在开发过程中,可以减少不必要的讨论, 从而并行开发,可以极大的提升开发效率。

另外一个好处,当网站进行改版后,服务端接口进行调整时,并不影响到前端的功能。

接口化开发概念:
1-前端请求后台
2-后台处理,返回数据 仓库
3-前端渲染

$.ajax({
    type: //后台决定
    url: //后台决定
    data: //后台决定
    dataType: //后台决定            
})

项目中,前后配合 依赖接口文档:

注册接口

表单序列化

jquery提供了一个serialize()方法序列化表单,说白就是将表单中带有name属性的所有参数拼成一个格式为name=value&name1=value1这样的字符串。方便我们获取表单的数据。

//serialize将表单参数序列化成一个字符串。必须指定name属性
//name=hucc&pass=123456&repass=123456&mobile=18511249258&code=1234
$('form').serialize();

jquery的ajax方法,data参数能够直接识别表单序列化的数据data:$('form').serialize()

$.post({
  url:"register.php",
  data:$('form').serialize(),
  dataType:'json',
  success:function (info) {
    console.log(info);
  }
});

需求文档

//注册功能
//总需求:点击注册按钮,向服务端发送请求
//需求1:表单校验
  //1.1 用户名不能为空,否则提示"请输入用户名"
  //1.2 密码不能为空,否则提示"请输入密码"
  //1.3 确认密码必须与密码一直,否则提示"确认密码与密码不一致"
  //1.4 手机号码不能为空,否则提示"请输入手机号码";
  //1.5 手机号码格式必须正确,否则提示"手机号格式错误"
  //1.6 短信验证码必须是4位的数字,否则提示"验证码格式错误"
//需求2:点击注册按钮时,按钮显示为"注册中...",并且不能重复提交请求
//需求3:根据不同响应结果,处理响应
     //3.1显示注册结果
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>表单注册</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            background-color: #F7F7F7;
        }

        ul {
            margin: 0;
            padding: 50px;
            list-style: none;
        }

        .register {
            width: 800px;
            margin: 50px auto;
            background-color: #FFF;
            border: 1px solid #CCC;
            border-radius: 5px;
        }

        li {
            display: flex;
            margin: 20px 0;
        }
        
        label, input {
            display: block;
            float: left;
            height: 46px;
            font-size: 24px;
            box-sizing: border-box;
            color: #333;
        }

        label {
            width: 200px;
            line-height: 46px;
            margin-right: 30px;
            text-align: right;
        }

        input {
            width: 320px;
            padding: 8px;
            line-height: 1;
            outline: none;
            position: relative;
        }

        input.code {
            width: 120px;
        }

        input.verify {
            width: 190px;
            margin-left: 10px;
        }

        input.disabled {
            background-color: #CCC !important;
        }

        input[type=button] {
            border: none;
            color: #FFF;
            background-color: #E64145;
            border-radius: 4px;
            cursor: pointer;
        }

        .tips {
            position: fixed;
            top: 0;
            width: 100%;
            height: 40px;
            text-align: center;
        }

        .tips p {
            min-width: 300px;
            max-width: 400px;
            line-height: 40px;
            margin: 0 auto;
            color: #FFF;
            display: none;
            background-color: #C91623;
        }

        input.gray {
            background-color: #ccc;
        }
    </style>
</head>
<body>
    <div class="register">
        <form id="ajaxForm">
            <ul>
                <li>
                    <label for="">用户名</label>
                    <input type="text" name="name" class="name">
                </li>
                <li>
                    <label for="">请设置密码</label>
                    <input type="password" name="pass" class="pass">
                </li>
                <li>
                    <label for="">请确认密码</label>
                    <input type="password" name="repass" class="repass">
                </li>
                <li>
                    <label for="">验证手机</label>
                    <input type="text" name="mobile" class="mobile">
                </li>
                <li>
                    <label for="">短信验证码</label>
                    <input type="text" name="code" class="code">
                    <input type="button" value="获取验证码" class="verify">
                </li>
                <li>
                    <label for=""></label>
                    <input type="button" class="btn" value="立即注册">
                </li>
            </ul>
        </form>
    </div>
    <!-- 提示信息 -->
    <div class="tips">
        <p>aaa</p>
    </div>
    <script src="../../jquery-1.12.4.min.js"></script>
    <script>
        // 1-点击注册按钮,获取表单数据
        // 2-验证表单数据是否合理,在数据合理情况,先后台发送请求进行注册
        // 3-监听服务器响应, 获取注册结果,并显示

        $('.btn').click(function () {

            // var regTel = /^1\d{10}$/;

            // console.log(regTel.test('22312312312'));
            
            //获取表单数据
            // var name = $('.name').val();
            // var pass = $('.pass').val();
            // var repass = $('.repass').val();
            // ... 
            // 后台需要什么数据格式: 
            // name=zs&age=18&sex=m
            // 上面的变量还需要进行拼接!!
            // jquery提供的表单序列化 (格式化)
            // name=zs&pass=123&repass=123&mobile=123&code=123
            // 原理:获取表单name属性和value属性进行拼接
            var formData = $('#ajaxForm').serialize();
            // console.log(formData);

            //$.ajax终止ajax请求  return false;

            //先把$.ajax框架写出
            $.ajax({
                type: 'post',
                url:'./register.php',
                data: formData, //也可以直接传递name=zs&age=18字符串 
                timeout: 10000, //超时,
                dataType: 'json', //把返回数据以何种类型进行处理
                beforeSend: function () {
                    //请求发送之前,做数据验证,如果数据不合理,程序到此结束
                    //1-验证用户名
                    if ($('.name').val().trim().length == 0) {
                        //显示提示信息
                        $('.tips p').fadeIn(500)
                        .delay(1000)  //让动画暂停 
                        .fadeOut(500)
                        .text('亲,用户名不能为空哦!');
                        // 终止请求 【只写return不能终止ajax请求,要写return false,这是ajax中的固定写法】
                        return false;
                    }

                    //2-验证密码
                    if ($('.pass').val().length < 6) {
                        //显示提示信息
                        $('.tips p').fadeIn(500)
                        .delay(1000)  //让动画暂停 
                        .fadeOut(500)
                        .text('亲,密码长度不能小于6位哦!');
                        //终止请求
                        return false;
                    }
                    // //3-验证密码是否一致
                    // if ($('.pass').val() != $('.repass').val()) {
                    //     //显示提示信息
                    //     $('.tips p').fadeIn(500)
                    //     .delay(1000)  //让动画暂停 
                    //     .fadeOut(500)
                    //     .text('亲,两次密码不一样哟!');
                    //     //终止请求
                    //     return false;
                    // }
                    // //验证手机号:
                    // // 规则: 1开头,后面跟10个数字
                    // var regTel = /^1\d{10}$/;

                    // //4-验证手机号
                    // if ( !regTel.test( $('.mobile').val() ) ) {
                    //     //显示提示信息
                    //     $('.tips p').fadeIn(500)
                    //     .delay(1000)  //让动画暂停 
                    //     .fadeOut(500)
                    //     .text('亲,手机必须是1开头的11位数字呀!');
                    //     //终止请求
                    //     return false;
                    // }

                    // //5-验证验证码的长度是否4为
                    // if ( $('.code').val().length != 4 ) {
                    //     //显示提示信息
                    //     $('.tips p').fadeIn(500)
                    //     .delay(1000)  //让动画暂停 
                    //     .fadeOut(500)
                    //     .text('亲,验证码格式有误哦!');
                    //     //终止请求
                    //     return false;
                    // }

                    // 程序执行到此,说明以上所有验证都通过了,马上可以发送请求了
                    // 改变按钮的颜色和文字,给用户提示,请求正在发送,不要着急...
                    // 禁用按钮,防止用户重复提交
                    // disabled checked selected 用 prop();
                    $('.btn').addClass('gray').val('正在注册...').prop('disabled', true);
                    
                },
                success:function (info) {
                    //注册成功,显示注册结果
                    console.log(info);      
                    if (info.code == 200) {
                        alert(info.msg);
                    }              
                    
                },
                error: function () {
                    console.log('请求出错了');                    
                },
                complete: function () {
                    //请求完成后,清空表单
                    // 把按钮取消禁用,去掉类名,设置颜色(复位)
                    $('.btn').removeClass('gray').val('立即注册').prop('disabled', false);
                }
            })
        });
    </script>

</body>
</html>
<?php 
    // echo '<pre>';
    // print_r($_POST);
    // echo '</pre>';

    //服务器 获取前端数据,判断数据是否合理,
    // 如果合理,注册成功,添加到数据库
    // 如果用户名不为空就注册成功
    $info = [];
    if (!empty($_POST['name'])) {
        //注册成功
        $info = [
            "code" => 200,
            "msg" => "注册成功"
        ];
    } else {
        //注册失败
        $info  = [
            "code" => 100,
            "msg" => "注册失败"
        ];
    }

    echo json_encode($info);
    // sleep(3);
?>

猜你喜欢

转载自www.cnblogs.com/jianjie/p/12383775.html