美文网首页
ajax简单封装

ajax简单封装

作者: kino2046 | 来源:发表于2020-02-16 02:45 被阅读0次

    ajax同源非同源

            非同源:跨域

                http://www.kaikeba.com:443/news/id/1

                同源:协议(http,https)  域名(www.kaikeba.com,localhost,127.0.0.1)  端口:443 一样 同源;有一个不一样 跨域


    ajax简单封装

    <!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>

    <!-- <form enctype="application/x-www-form-urlencoded"></form> -->

    </body>

    <script>

        ajax({

            url: "/test",

            method: "post",

            data: {

                hello: "你好",

                height: "178cm"

            },

            success(res) {

                console.log(res)

            }

        })

        function ajax(opts) {

            let newOpts = Object.assign({          //方法用于对象的合并

                url: "",

                method: "get",

                data: "",

                async:true,

                headers:{

                   "content-type":"application/x-www-form-urlencoded" 

                },

                success() { }

            }, opts);

            let xhr = new XMLHttpRequest();

            // get 是通过querystring方式传参数;            post :send(data)       data:name=zhangsan&age=20

            // get url:/xml     data:{name:zhangsan,age:20}--->/xml?name=zhangsan&age=20&height=178            querystring是查询参&连接,不加引号

            if (newOpts.method.toLowerCase() === "get") {             //不管大写小写

                xhr.open(newOpts.method, newOpts.url + "?"+ o2u(newOpts.data),newOpts.async);

            }else{

                xhr.open(newOpts.method, newOpts.url,newOpts.async);

            }

            xhr.setRequestHeader("content-type",newOpts.headers['content-type']);

            xhr.onload=function(){

                newOpts.success(JSON.parse(xhr.responseText));

            }

            let sendData = null

            if(newOpts.method.toLowerCase()==="post"){

                // name=zhangsan&age=20&height=178

                sendData = o2u(newOpts.data);

            }

            xhr.send(sendData);

            // let obj = {

            //     name:"张三",

            //     age:20

            // }

            // console.log(o2u(obj));

            function o2u(obj) {

                // ["hello","height"] --> 0,1

                let keys = Object.keys(obj);

                let values = Object.values(obj);

                return keys.map((key, k) => {

                    console.log(k)

                    return key + "=" + values[k];

                }).join("&");

            }

        }

    </script>

    </html>


    相关文章

      网友评论

          本文标题:ajax简单封装

          本文链接:https://www.haomeiwen.com/subject/ucuufhtx.html