ajax

119 阅读1分钟

AJAX 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。

<body>
    <!-- get和post 实战用法的区别 -->
    <!-- 1、get 会把参数放在url上显示 所以不安全  -->
    <!-- 2、post 不会把参数显示到url上 登录的时候推荐使用psot -->
    <!-- 3、get 传输的数据有限制 2kb 只支持 ASCII 字符 -->
    <!-- 4、post 传输没有大小限制,没有限制,也允许二进制数据
    传输文件 或者 图片的时候 使用post请求 -->

    <!-- form表单提交数据 是会把整个页面进行刷新 重新加载整个网页 -->
    <form action="" method="post">
        密码:<input type="password" name="password">
        <input type="submit" value="submit">
    </form>
    <br>
    <button onclick="ajaxFn()">ajax获取数据</button>
    <script>
        function ajaxFn() {
            /* Ajax 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术
        局部更新
 */
            /* 创建Ajax的步骤 */

            /* 第一步 创建Ajax对象 */
            /* new一个XMLHttpRequest的实例化对象 */
            let xhr = new XMLHttpRequest();
            console.log(xhr)


            /* 第二部 连接到服务器 */
            /* 
                open(方法,文件名,同步异步)
                参数一:post/get
                参数二:请求的文件名
                参数三:同步(false)  异步(true)
            */

            /* 获取文件的数据一定要使用异步 */
            /* 读取文件需要时间 */
            xhr.open('get', 'abc.txt', true)

            /* 第三步 发送请求 */
            xhr.send();

            /* 第四步 接收返回值 */
            /* 监听返回值 */
            /* onreadystatechange就是用来监听readyState值的变化的 */
            xhr.onreadystatechange = function () {
                /* xhr.responseText 通过ajax请求获得的数据 */
                console.log(xhr.responseText)
            }
            /* 使用live server 打开页面 */
        }

        /* 同步异步区别 */
        /*
        同步交互:指发送一个请求,需要等待返回,然后才能够发送下一个请求,有个等待过程
异步交互:指发送一个请求,不需要等待返回,随时可以再发送下一个请求,即不需要等待

        */



    </script>
</body>
复制代码

状态码的变化

<body>
    <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)
                console.log('响应状态码',xhr.status);
            }
        }

        /* 响应状态码 */
        /* status 为200 表示请求成功 
            201 也表示成功 
            304 从http请求中的缓存拿来的数据
        */
        /* status 为404 not found 找不到地址  地址写错了 未找到页面
        多数前端问题 
        403 表示没有权限*/
        /* status 为500 表示服务端代码错误 */


        /* 使用xhr请求 txt内容 并显示到页面上 */
    </script>
</body>
复制代码

原生方法操作真实接口

<body>
    <button onclick="login()">请先登录,再获得数据</button>
    <p>
        <button onclick="getUserInfo()">获取用户数据</button>
    </p>
    <!-- 这个真实的接口 是用来登录的  所以使用post方式登录 -->
    <script>
        function getUserInfo(){
            /* 需要先判断有没有token 有token 就不提示直接获取数据
            没有token 就给个提示 请先登录 获取token 不执行下面的内容 */
            if(!localStorage.token){
                alert('请先登录,获取token!!')
                return;
            }
            let xhr = new XMLHttpRequest();
            /* pagenum=1 表示取第一页的数据 */
            /* pagesize=5 表示显示5条数据 */
            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>
</body>


作者:昨夜风清
链接:juejin.cn/post/705147… 来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。