Ajax请求、json、以及原生方法操作接口

1.Ajax请求:

<button onclick="ajaxFn()">ajax获取数据</button>

    <script>

        function ajaxFn (){

        let xhr = new XMLHttpRequest();

        /* 0:请求未初始化(还没有调用到open方法) */

        console.log('请求未初始化',xhr.readyState);

        xhr.open('get','abc.txt',true)

        xhr.send();

        /* 1:服务器连接已建立(已调用send方法,正在发生请求) */

        console.log('服务器连接已经建立',xhr.readyState);

        /* onreadystatechange就是用来监听readyState值的变化的 */

        xhr.onreadystatechange = function(){

            /* 2:请求已接受(send方法完成.已接收到全部响应内容) */

            if(xhr.readyState==2){

                console.log('请求已接收',xhr.readyState);

            }

            /* 3.请求处理中(解析响应内容) */

            if(xhr.readyState==3){

                console.log('请求处理中',xhr.readyState);

            }

            /* 4.请求已完成,且响应已就绪 */

            if(xhr.readyState==4){

                console.log('请求已完成',xhr.readyState);

            }

            /* xhr.responseText通过Ajax请求获得数据 */

            /* console.log(xhr.responseText) */

        }

    }

        /* 响应状态码 */

        /* status为200,201(从缓存读取) 表示请求成功 */

        /* status为304,表示从http请求中的缓存拿来的数据 */

        /* status为404 not found 表示找不到页面 多数前端问题*/

        /* status为403 表示没有权限,禁止访问 */

        /* status为500 表示服务端代码错误 */

    </script>

2.JSON:

JSON写法模板:

{

    "name":"zhangsan",

    "age":30,

    "flag":true,

    "city":null,

    "arrList":[{

        "car":"ct5"

    },{

        "car":"ct7"

    },{

        "car":"ct6"

    }]

}

JSON基础概念:

<!--

         JSON是一种轻量级的数据交换格式,它基于 ECMAScript 的一个子集,采用完全独立于编程语言的文本格式来存储和表示数据

     -->

     <!--

        JSON里面可以写[] 也可以{}

        但是必须使用双引号

        数据在名称/值对中

        数据由逗号分隔

        大括号保存对象

        中括号保存数组

        可以是数字、字符串、逻辑值、数组、对象、null

      -->

    <button onclick="getData()">获取用户信息</button>

    <div id="userInfo"></div>

    <script>

        /* JSON是一种轻量级的数据交换格式 */

        function getData() {

            let userInfo = document.getElementById('userInfo');

            let xhr = new XMLHttpRequest();

            xhr.open('get', '6.date.json', true);

            xhr.send();

            xhr.onreadystatechange = function () {

                if (xhr.readyState == 4) {

                    /* document.write(JSON.parse(xhr.responseText)) */

                    let obj = JSON.parse(xhr.responseText)

                    let str =

                        '<h1>姓名:' + obj.name + '</h1>' +

                        '<h1>年纪:' + obj.age + '</h1>' +

                        '<h1>城市:' + obj.city + '</h1>' +

                        '<h1>汽车:</h1>';

                    if (obj.arrList.flag) {

                        for (var i = 0; i < obj.arrList.length; i++) {

                            str += '<h1>' + obj.arrList[i].car + '</h1>';

                        }

                    }

                    userInfo.innerHTML = str

                }

            }

        }

    </script>

JSON练习:

<style>

        * {

            margin: 0;

            padding: 0;

        }

        .box {

            width: 100%;

            height: 1.5rem;

            border-bottom: 1px solid #ccc;

        }

        .t {

            font-size: 16px;

            margin: .05rem;

        }

        .imgs {

            width: 100%;

            display: flex;

        }

        .imgs img {

            width: 33%;

            height: 1rem;

            margin: .05rem;

            display: block;

        }

    </style>

</head>

<body>

    <!-- <div class="box">

        <p class="t">看到她这张脸,我就知道未来的“偶像剧”有希望了</p>

        <div class="imgs">

            <img src="https://ss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=1490879384,162462824&fm=30&app=106&f=JPEG?w=312&h=208&s=3282DD4FCCDA45DEF0057CBA03006011" alt="">

            <img src="https://ss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=1490879384,162462824&fm=30&app=106&f=JPEG?w=312&h=208&s=3282DD4FCCDA45DEF0057CBA03006011" alt="">

            <img src="https://ss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=1490879384,162462824&fm=30&app=106&f=JPEG?w=312&h=208&s=3282DD4FCCDA45DEF0057CBA03006011" alt="">

        </div>

    </div> -->

    <script>

        let body = document.querySelector('body');

        let xhr = new XMLHttpRequest();

        xhr.open('get', 'newsData.json', true);

        xhr.send();

        xhr.onreadystatechange = function () {

            if (xhr.readyState == 4) {

                let obj = JSON.parse(xhr.responseText);

                let str = ''

                for (var i = 0; i < obj.length; i++) {

                    str +=

                        '<div class="box">' +

                            '<p class="t">' + obj[i].title + '</p>' +

                            '<div class="imgs">' +

                                '<img src="' + obj[i].img1 + '" alt="">' +

                                '<img src="' + obj[i].img2 + '" alt="">' +

                                '<img src="' + obj[i].img3 + '" alt="">' +

                            '</div>' +

                        '</div>';

                }

                body.innerHTML = str;

            }

        }

    </script>

3.原生方法操作接口:

<body>

    <button onclick="login()">请先登录</button>

    <p>

        <button onclick="getUserInfo()">获取用户数据</button>

    </p>

    <!-- 真实接口 用来登录的

          使用post方式登录 -->

    <script>

        function getUserInfo(){

            /* pagenum=1 表示获取第一页的数据 */

            /* pagessize=5 表示显示5条数据 */

            if(!localStorage.token){

                 alert('请先登录获取token')

                 return;

            }

            let xhr = new XMLHttpRequest();

            let url = 'http://timemeetyou.com:8889/api/private/v1/users?pagenum=1&pagesize=6';

            xhr.open('get',url,true);

            xhr.setRequestHeader('Authorization',localStorage.token)

            xhr.send();

            xhr.onreadystatechange = function(){

                if(xhr.readyState == 4){

               let res = JSON.parse(xhr.responseText);

               console.log(res);

            }



        }

    }

       function login(){

       let xhr = new XMLHttpRequest();

       let url = 'http://timemeetyou.com:8889/api/private/v1/login';

       xhr.open('post',url,true);

       let params = {username:"admin",

           password:"123456"};

           /* post需要添加请求头 */

           /* 请求回来的内容是json格式 */

           /*  Content-type 表示请求内容的类型*/

           /* application/json 表示请求内容类型的具体的值 */

           xhr.setRequestHeader("Content-type","application/json")

       xhr.send(JSON.stringify(params));

       xhr.onreadystatechange = function(){

           if(xhr.readyState == 4){

               let res = JSON.parse(xhr.responseText);

               console.log(res);

               localStorage.token = res.data.token;

               // location.href="shop.html"

           }

       }

    }

    </script>



©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容