• ajax与jsonp中的几个封装函数


    首先是ajax里的get

    在页面上添加几个标签用作测试

    <body>
        <input type="text" id="user">
        <input type="text" id="pass">
        <input type="button" id="btn">
    </body>

    js部分:

        var ouser = document.getElementById("user")
        var opass = document.getElementById("pass")
        var obtn = document.getElementById("btn")
    
        obtn.onclick = function(){
            var url = "http://localhost/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();
        }

    因为浏览器会优先拿出缓存中的数据,这样我们就不能实现无刷新加载新数据了。所以,拼接时间戳是为了浏览器每次请求的地址都不相同,以此来欺骗浏览器。

    然后是post的封装

    document.onclick = function(){
            var url = "http://localhost/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);
        }

    GET+POST的封装如下:

    document.onclick = function(){
            ajax({
                // type:"get",                 //发送方式,可选,默认get
                url:"http://localhost/1908/ajax/data/data.php",   //要请求的地址,必选
                success:function(res){         //请求成功之后的函数,必选
                    console.log(res)
                },
                // data:{                      //要发送的数据,可选,默认不发
                //     user:"admin",
                //     pass:13123121123
                // },
                // error:function(res){         //请求失败之后的函数,可选,默认不处理
                //     console.log(res)
                // },
                // timeout:10                  //请求超时的时间,可选,默认2000
            })
        }
    
        function ajax(options){
            // 1.处理默认参数
            var {type,url,success,error,data,timeout} = options;
            type = type || "get";
            data = data || {};
            timeout = timeout || 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()
            }
        }

    封装jsonp:

    document.onclick = function(){
            var url = "http://127.0.0.1/jsonp/data/jsonp.php"
            jsonp(url,function(res){
                console.log(res)
            },{
                user:"root"
            })
        }
    
        function jsonp(url,cb,data){
    
            data = data || {};
            var str = "";
            for(var i in data){
                str += `${i}=${data[i]}&`;
            }
    
            var script = document.createElement("script");
            script.src = url + "?" + str;
            document.body.appendChild(script);
    
            window.fn = function(res){
                console.log(res)
            }
    
        }

    放在博客上主要也是方便自己以后好找。看过的人觉得有点用就好

  • 相关阅读:
    leetcode211
    leetcode209
    leetcode201
    leetcode1396
    leetcode1395
    leetcode1394
    leetcode1386
    leetcode1387
    leetcode1382
    leetcode1376
  • 原文地址:https://www.cnblogs.com/funseey/p/11523240.html
Copyright © 2020-2023  润新知