zoukankan      html  css  js  c++  java
  • ajax封装

    GET

    <!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>Document</title>
    </head>
    <body>
        <h2>测试ajax-get的无刷新加载新数据</h2>
        <input type="text" id="user">
        <input type="text" id="pass">
        <input type="button" id="btn">
    </body>
    <script>
        var ouser = document.getElementById("user")
        var opass = document.getElementById("pass")
        var obtn = document.getElementById("btn")
    
        obtn.onclick = function(){
            var url = "http://localhost/1908/ajax/data/data.php";
    
            ajaxGet(url,function(res){
                console.log(res)
            },{
                user:ouser.value,
                pass:opass.value
            });
        }
    
        function ajaxGet(url,cb,data){
            // 1.处理data的默认值
            data = data || {};
            // "url?user=admin&pass=123"
            // 2.解析要发送的数据
            var str = "";
            for(var i in data){
                str += `${i}=${data[i]}&`;
            }
            // 3.处理时间戳
            var d = new Date();
            // 4.拼接url,实现数据的发送和时间戳的拼接
            url = url + "?" + str + "__qft="+d.getTime();
    
            // console.log(url)
    
            // 5.ajax的正式开启,请求,接收
            var xhr = new XMLHttpRequest();
            xhr.open("GET",url,true);
            xhr.onreadystatechange = function(){
                if(xhr.readyState == 4 && xhr.status == 200){
                    cb(xhr.responseText);
                }
            }
            xhr.send();
        }
    
    
        // 解决并没有出现的bug:
            // 浏览器有缓存
            // 每次浏览器请求相同地址,会优先查找缓存
            // 如果能够让浏览器每次请求的地址,都不一样
            // 在url后拼接时间戳,以此欺骗浏览器
    
    </script>
    </html>

    POST

    <!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>Document</title>
    </head>
    <body>
        
    </body>
    <script>
    
        document.onclick = function(){
            var url = "http://localhost/1908/ajax/data/data.php";
            ajaxPost(url,function(res){
                console.log(res)
            },{
                user:"admin",
                pass:"123123"
            })
        };
    
        function ajaxPost(url,cb,data){
            data = data || {};
            var str = "";
            for(var i in data){
                str += `${i}=${data[i]}&`;
            }
            // "user=admin&pass=123&"
            // post发送的数据,不在url身上
    
            var xhr = new XMLHttpRequest();
            // 1.修改ajax的执行方式为post
            xhr.open("post",url,true);
            xhr.onreadystatechange = function(){
                if(xhr.readyState == 4 && xhr.status == 200){
                    cb(xhr.responseText)
                }
            }
            // 2.设置发送数据的格式为表单数据
            xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            // 3.将原来在url身上拼接的数据,交给send发送
            xhr.send(str);
        }
    </script>
    </html>

    GET AND POST

    <!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>Document</title>
    </head>
    <body>
        测试ajax的get和post二合一的封装
    </body>
    <script>
    
        document.onclick = function(){
            ajax({
                // type:"get",                 //发送方式,可选,默认get
                url:"http://localhost/ajax/data/data.php",   //要请求的地址,必选
                success:function(res){         //请求成功之后的函数,必选
                    console.log(res)//后台的数据
                },
                 data:{                      //要发送的数据,可选,默认不发
                     user:"admin",
                     pass:13123121123
                 },
                 error:function(res){         //请求失败之后的函数,可选,默认不处理,是一个回调函数被后面的error()执行
                     console.log(res)//请求失败输出404
                 },
                 timeout:10                  //请求超时的时间,可选,默认2000
            })
        }
    
        function ajax(options){  //options是上面传进来的对象,对象里面可以包裹对象。解构赋值,形参可以比实参多,多的那些为undefined
            // 1.处理默认参数
            var {type,url,success,error,data,timeout} = options;//解构赋值,分别代表提交方式,php库地址,成功了执行啥,失败了执行啥,传的数据,超时会怎么样
            type = type || "get";  //当不设置时就选择默认get
            data = data || {};    //当不设置时就不传数据
            timeout = timeout || 2000;    //当不设置时,默认为2000
    
            // 2.解析要发送的数据
            var str = "";
            for(var i in data){
                str += `${i}=${data[i]}&`;
            }
    
            // 3.根据方式,决定是否处理url
            if(type == "get"){
                var d = new Date();
                url = url + "?" + str + "__qft=" + d.getTime();
            }
    
            // 4.开启ajax
            var xhr = new XMLHttpRequest();
            // 注意:open中的方式
            xhr.open(type,url,true);
            xhr.onreadystatechange = function(){
                if(xhr.readyState == 4 && xhr.status == 200){
                    // 5.执行成功之前,先判断是否传入
                    success && success(xhr.responseText);
                    // 成功之后,不应有失败
                    error = null;
                }else if(xhr.readyState == 4 && xhr.status != 200){
                    // 6.执行失败之前,先判断是否传入
                    error && error(xhr.status);
                    // 失败之后,不应有成功
                    success = null;
                    // 且失败不应多次执行
                    error = null;
                }
            }
    
            // 7.如果请求超时,执行失败
            setTimeout(() => {
                error && error("timeout");
                // 失败之后,不应有成功
                success = null;
            }, timeout);
    
            // 8.最后根据type的方式,决定send的发送内容和格式
            if(type == "post"){
                xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
                xhr.send(str)
            }else{
                xhr.send()
            }
        }
    
    </script>
    </html>

    后台PHP代码

    <?php
    
        
        $u = @$_REQUEST["user"];
        $p = @$_REQUEST["pass"];
    
        echo "这是前端的ajax发送的数据,现在再还给前端:".$u."-------".$p;
    
    
    
    
        
    
        // $user = "admin";
        // $pass = "789654";
    
        // if($u == $user && $p == $pass){
        //     echo "ok";
        // }else{
        //     echo "no";
        // }
    
    ?>
  • 相关阅读:
    032 代码复用与函数递归
    031 实例7-七段数码管绘制
    030 函数的定义与使用
    029 函数和代码复用
    2.4 Buffer
    2.3 字符串链接
    2.2 去除字符串特别字符
    2.1 字符串查询
    存储数据_文件读写
    template模板
  • 原文地址:https://www.cnblogs.com/hy96/p/11496268.html
Copyright © 2011-2022 走看看