jq中的ajax

192 阅读1分钟

post

    <script src="./jquery-1.12.4.js"></script>
    <script>
        $('button').click(function () {
            // $.ajax({
            //     url: "http://timemeetyou.com:8889/api/private/v1/login",
            //     method: "post",
            //     data: {
            //         username: 'admin',
            //         password: '123456'
            //     },
            //     dataType: 'json',
            //     success: function (res) {
            //         console.log(res);
            //     },
            // })
            let url = "http://timemeetyou.com:8889/api/private/v1/login";
            /* $.post有三个参数 第一参数表示接口地址 第二个参数表示传输的数据 
            第三个参数表示成功后的回调函数 */
            $.post(url,{username:'admin',password:'123456'},function(res){
                console.log(res);
            })

        })

callback

<button id="btn">点</button>
    <script src="./jquery-1.12.4.js"></script>
    <script>
        $("#btn").click(function () {
            $.ajax({
                url: "http://localhost/a.php",
                type: "get",
                //定义发送jsonp请求
                dataType: 'jsonp',
                //更改定义的参数名
                jsonp: 'kyFn',//修改callback名称,但是php中也要修改成相对应的函数名
                //指定jsonp发送的回调函数名(可以任意起名字,无需对应)
                jsonpCallback: 'hyly',
                success: function (info) {
                    console.log(info);
                }
            });
        })

    </script>

超文本传输协议

    <!-- 
        超文本传输协议(HTTP,HyperText Transfer Protocol)是互联网上应用最为广泛的一种网络协议
设计HTTP最初的目的是为了提供一种发布和接收HTML页面的方法
        一次HTTP操作称为一个事务,其工作过程可分为四步
     -->
     <!-- 
         OPTIONS	返回服务器针对特定资源所支持的HTTP请求方法
HEAD	向服务器索要与GET请求相一致的响应,只不过响应体将不会被返回
GET	向特定的资源发出请求 一般用户请求数据会被经常使用
POST	向指定资源提交数据进行处理请求 一般用于登录 数据保密 还可以用与文件传输
PUT	向指定资源位置上传其最新内容 需要修改数据的时候和更新数据的时候 
DELETE	请求服务器删除Request-URI所标识的资源 删除数据的时候使用  
TRACE	回显服务器收到的请求,主要用于测试或诊断  
CONNECT	HTTP/1.1协议中预留给能够将连接改为管道方式的代理服务器 
HTTP/1.1 例如:http://   HTTP/2 例如:https:// 加密 https://www.baidu.com/
PATCH	实体中包含一个表,表中说明与该URI所表示的原内容的区别

- GET(SELECT):从服务器取出资源(一项或多项)。
- POST(CREATE):在服务器新建一个资源。
- PUT(UPDATE):在服务器更新资源(客户端提供改变后的完整资源)。
- PATCH(UPDATE):在服务器更新资源(客户端提供改变的属性)。
- DELETE(DELETE):从服务器删除资源。
- HEAD:获取资源的元数据。
- OPTIONS:获取信息,关于资源的哪些属性是客户端可以改变的。
-->
<!-- 
    原生的方式
    创建Ajax对象  var oAjax=new XMLHttpRequest();

连接到服务器 oAjax.open("GET","abc.txt",true);

发送请求send oAjax.send();

接收返回值
oAjax.onreadystatechange=function(){
		if (oAjax.readyState==4 && oAjax.status==200){
				alert("请求成功"+oAjax.responseText);
		}
}


 -->
</body>

jq中的ajax

        $('button').click(function(){
            // $.ajax({
            //     /* 异步 默认为true  */
            //     /* false表示同步 改同步渲染页面会出现白屏现象*/
            //     async:true,
            //     /* 是否设置浏览器的缓存功能 true 设置缓存
            //     false不设置缓存 每次请求都是新的请求 */
            //     cache:true,
            //     /* 请求的接口 */
            //     // url:"http://timemeetyou.com:8889/api/private/v1/login",
            //     url:"./123.txt",
            //     /* 请求的方式 post有加密功能 */
            //     // method:"post",
            //     method:"get",
            //     /* 发送到服务器的数据 */
            //     // data:{
            //     //     username:'admin',
            //     //     password:'123456'
            //     // },
            //     /* 预期服务器返回的数据类型 json jsonp*/
            //     dataType:'json',
            //     /* 在一个 jsonp 请求中重写回调函数的名字 */
            //     /* 这里fn需要和后台的代码对应 */
            //     jsonp:"fn",
            //     /* 为 jsonp 请求指定一个回调函数名 */
            //     /*  callbackFn 是前端配置的 */
            //     jsonpCallback:"callbackFn",
            //     /* 请求成功之后 执行的回调函数 */
            //     // success:function(res){
            //     //     /* success后面的方法里面的形参res表示后台返回的数据 */
            //     //     console.log( res );
            //     // },
            //     /* 请求失败时调用此函数 */
            //     error:function(err){
            //         console.log(err)
            //     }
            // })
           
        })
        // function callbackFn(res){
        //     console.log(res)
        // }

        /* 
        
        参数	类型	描述
options	Object	可选,AJAX 请求设置,所有选项都是可选的
async	Boolean	默认值: true。默认设置下,所有请求均为异步请求。如果需要发送同步请求,请将此选项设置为 false
cache	Boolean	默认值: true,dataType 为 script 和 jsonp 时默认为 false。设置为 false 将不缓存此页面
data	String	发送到服务器的数据
dataType	String	预期服务器返回的数据类型
error	Function	请求失败时调用此函数
success	Function	请求成功后的回调函数
jsonp	String	在一个 jsonp 请求中重写回调函数的名字
jsonpCallback	String	为 jsonp 请求指定一个回调函数名
         */
    </script>

练习1和$get

    <h1></h1>
    <script src="./jquery-1.12.4.js"></script>
    <script>
        $('button').click(function(){
            // $.ajax({
            //     url:"./login1.txt",
            //     method:'get',
            //     async:true,
            //     dataType:'json',
            //     success:function(res){
            //         console.log(res);
            //         $('h1').html(`姓名:${res.name},${res.msg}`)
            //         $('button').fadeOut('slow')
            //     },
            //     error:function(){
            //         $('h1').html('请求失败')
            //     }
            // })
            /* $.get 方法 不需要传参 第一个是接口地址 第二个回调函数 */
            /* 需要传参 第一个是接口地址 第二个传输的数据 第三个是成功后的回调函数  */
            // $.get('./login.txt',{name:'zhangsan',age:30},function(data){
            //     let res = JSON.parse(data)
            //     $('h1').html(`姓名:${res.name},${res.msg}`)
            //     $('button').fadeOut('slow')
            // })
            // $.get('./login.txt?name=zhangsan&age=30',function(data){
            //     let res = JSON.parse(data)
            //     $('h1').html(`姓名:${res.name},${res.msg}`)
            //     $('button').fadeOut('slow')
            // })
        })
    </script>

练习2

    <button id="login">登录</button>
    <div>
        <p>
            用户名: <input type="text" id="username">
        </p>
        <p>
            密码: <input type="password" id="password">
        </p>
        <p>
            邮箱: <input type="text" id="email">
        </p>
        <p>
            手机号: <input type="text" id="mobile">
        </p>
        <input type="submit" value="添加" id="submit">
        <h1 id="msg" style="color:red;"></h1>
    </div>
    <input type="text" id="userid"> 
    <button id="query">查询</button>
    <table border="1">
        <thead>
            <tr>
                <th>姓名</th>
                <th>电话</th>
                <th>电子邮箱</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>

        </tbody>
    </table>

    <script src="./jquery-1.12.4.js"></script>
    <script>
         let url = "http://timemeetyou.com:8889/api/private/v1/";
        /* 登录功能 */
        $('#login').click(function () {
            $.post(url+'login',{username:'admin',password:'123456'},function(res){
                localStorage.token = res.data.token;
                $('#login').slideUp('slow')
                /* 得到token之后调用获取用户列表数据 */
                getUsers();
            })
        })
        /* 获取用户列表数据 */
        function getUsers(){
            $.ajax({
                url:url+'users',
                headers:{
                    Authorization:localStorage.token
                },
                data:{
                    pagenum:1,
                    pagesize:50
                },
                success:function(res){
                    /* 插入最新的数据之前 
                    先清空之前的数据 */
                    $('tbody').html('');
                    for(var i in res.data.users){
                        $('tbody').append(
                            `
                                <tr>
                                    <td>${res.data.users[i].username}</td>
                                    <td>${res.data.users[i].mobile}</td>
                                    <td>${res.data.users[i].email}</td>
                                    <td><button onclick="del(${res.data.users[i].id})">删除</button></td>
                                </tr>
                            `
                        )
                    }
                    
                }
            })
        }
        $('#query').click(function(){
            $.ajax({
                url:url+'users/'+$('#userid').val(),
                headers:{
                    Authorization:localStorage.token
                },
                success:function(res){
                    /* 出现提示 */
                    $('#msg').html(res.meta.msg)
                    /* 过三秒 提示消失 */
                    setTimeout(function(){
                        $('#msg').html('')
                    },3000)
                    /* 更新最新的表格信息 */
                    // getUsers();
                    $('tbody').html('');
                    $('tbody').append(
                        `
                            <tr>
                                <td>${res.data.username}</td>
                                <td>${res.data.mobile}</td>
                                <td>${res.data.email}</td>
                                <td><button onclick="del(${res.data.id})">删除</button></td>
                            </tr>
                        `
                    )
                   
                }
            })
        })
        function del(id){
            console.log(id);
            $.ajax({
                url:url+'users/'+id,
                method:'delete',
                headers:{
                    Authorization:localStorage.token
                },
                success:function(res){
                    /* 出现提示 */
                    $('#msg').html(res.meta.msg)
                    /* 过三秒 提示消失 */
                    setTimeout(function(){
                        $('#msg').html('')
                    },3000)
                    /* 更新最新的表格信息 */
                    getUsers();
                }
            })
        }

        $('#submit').click(function(){
            $.ajax({
                url:url+'users',
                method:"post",
                headers:{
                    Authorization:localStorage.token
                },
                data:{
                    username:$('#username').val(),
                    password:$('#password').val(),
                    email:$('#email').val(),
                    mobile:$('#mobile').val(),
                },
                success:function(res){
                    /* 出现提示 */
                    $('#msg').html(res.meta.msg)
                    /* 过三秒 提示消失 */
                    setTimeout(function(){
                        $('#msg').html('')
                    },3000)
                    $('#username').val('')
                    $('#password').val('')
                    $('#email').val('')
                    $('#mobile').val('')
                    /* 更新最新的表格信息 */
                    getUsers();
                }
            })
        })
    </script>