JavaScript之Ajax初识(Ajax重要干货)

  • Post author:
  • Post category:java



目录


一.Ajax概念


二.url网址


1.url概念


2.url作用


3.url网址组成


三.JSON


四.案例-新闻列表


五.axios新增数据


axios五种请求方式


六.用户登录功能


七.业务状态码


八.问答机器人


完成效果图


​编辑


核心代码



一.Ajax概念

Ajax–全称(Asynchronous Javascript And XML),异步的JavaScript和XML,Ajax其实就是浏览器与服务器之间的一种异步通信方式

二.url网址

1.url概念

浏览器用于浏览资源, 服务器用于提供资源,那浏览器想要访问需要看到的资源, 就得知道资源的url网址,url, 统一资源定位符, 标记资源在网络中的位置。也称

网址


2.url作用

标记某个资源在网络中的唯一地址。只有通过URL地址,浏览器才能定位资源的存放位置,从而成功访问到对应的资源。

3.url网址组成

url网址组成由四个部分组成分别是:

  1. 协议
  2. 主机名
  3. 端口号(可省略)
  4. 资源存放的路径

三.JSON

JSON(全称:JavaScript Object Notation)是一种数据交换格式,它本质上是

用字符串的方式来表示对象

或数组


对象格式JSON字符串

  • key必须用双引号包起来
  • value 的值只能是字符串、数字、布尔值、null、数组、对象类型(可选类型只有这 6 种)

    const user = `{
     "name": "小红",
     "age": 20,
     "marry": true,
     "weight": 80,
     "hobby": ["吃饭", "睡觉", "打豆豆"],
     "address": {
      "province": "辽宁省",
      "city": "大连市"
     }
    }`

    拓展:JSON字符串和JS数据类型如何互相转换

  • JSON.stringify() JS数据类型转JSON字符串
  • JSON.parse() JSON字符串转成JS数据类型

四.案例-新闻列表

<!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>案例_新闻列表</title>
    <!-- 导入样式表 -->
    <style>
        .news-item {
            display: flex;
            border: 1px solid #eee;
            width: 700px;
            padding: 10px;
            margin-bottom: 5px;
        }

        .thumb {
            display: block;
            width: 230px;
            height: 140px;
            background-color: #ccc;
            margin-right: 10px;
        }

        .right-box {
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            font-size: 12px;
            flex: 1;
        }

        .title {
            font-size: 20px;
            font-weight: normal;
        }

        .tags span {
            display: block;
            float: left;
            background-color: #F0F0F0;
            line-height: 20px;
            padding: 0 10px;
            border-radius: 10px;
            margin-right: 8px;
        }

        .footer {
            display: flex;
            justify-content: space-between;
        }
    </style>
</head>

<body>
    <!-- 新闻列表 -->
    <div id="news-list">
        <!-- 新闻的 item 项 -->
        <div class="news-item">
            <img class="thumb" src="http://123.57.109.30:3006/images/5.webp" alt="" />
            <div class="right-box">
                <!-- 新闻标题 -->
                <h1 class="title">5G商用在即,三大运营商营收持续下降</h1>
                <div class="footer">
                    <div>
                        <!-- 新闻来源 -->
                        <span>胡润百富</span>&nbsp;&nbsp;
                        <!-- 发布日期 -->
                        <span>2019-10-28 10:14:38</span>
                    </div>
                    <!-- 评论数量 -->
                    <span>评论数:66</span>
                </div>
            </div>
        </div>
    </div>

    <script src="./js/axios.js"></script>
    <script>
        axios({
            url: 'http://hmajax.itheima.net/api/news',
            method: 'GET'
        }).then(res => {
            console.log(res.data.data);

            const arr = res.data.data

            let newObj = ''
            arr.map(function (item) {
                newObj += `
            <div class="news-item">
                <img class="thumb" src="${item.img}" alt="" />
                <div class="right-box">
                    <!-- 新闻标题 -->
                    <h1 class="title">${item.title}</h1>
                    <div class="footer">
                        <div>
                            <!-- 新闻来源 -->
                            <span>${item.source}</span>&nbsp;&nbsp;
                            <!-- 发布日期 -->
                            <span>${item.time}</span>
                        </div>
                        <!-- 评论数量 -->
                        <span>评论数:${item.cmtcount}</span>
                    </div>
                </div>
            </div>
                `
            })
            document.querySelector('#news-list').innerHTML = `${newObj}`
        })
    </script>
</body>

</html>

五.axios新增数据

axios五种请求方式

axios({
    url: '请求地址',
    method: 'POST',    // 一般来讲是POST
    data: {            // data: 对应要发给后端数据
        // 后端规定的参数名: 前端发给后端的值
    }
}).then(result => {
    console.log(result);
})

六.用户登录功能

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>11-12.案例_用户登录.html</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
    <style>
        html,
        body {
            background-color: #f8f8f8;
        }

        .login-box {
            width: 400px;
            position: fixed;
            top: 20%;
            left: 50%;
            transform: translateX(-50%);
            border: 1px solid #efefef;
            padding: 20px;
            border-radius: 4px;
            box-shadow: 1px 1px 5px #cfcfcf;
            background-color: #fff;
            transition: box-shadow 0.3s ease;
        }

        .login-box:hover {
            transition: box-shadow 0.3s ease;
            box-shadow: 1px 1px 20px #cfcfcf;
        }
    </style>
</head>

<body>
    <div class="login-box">
        <div class="form-group">
            <label for="username">Account</label>
            <!-- 账号 -->
            <input type="text" class="form-control" id="username" autocomplete="off">
            <small id="emailHelp" class="form-text text-muted">
                The available account is<strong>admin</strong>
            </small>
        </div>
        <div class="form-group">
            <!-- 密码 -->
            <label for="password">Password</label>
            <input type="password" class="form-control" id="password">
            <small id="emailHelp" class="form-text text-muted">The available password is
                <strong>123456</strong></small>

        </div>
        <button type="submit" class="btn btn-primary" id="btnLogin">Submit</button>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/axios@0.27.2/dist/axios.min.js"></script>

    <script>
        const btn = document.querySelector('#btnLogin')

        btn.addEventListener('click', function () {
            let username = document.querySelector('#username').value.trim()
            let password = document.querySelector('#password').value.trim()


            axios({
                url: 'http://ajax-api.itheima.net/api/login',
                // url: 'http://hmajax.itheima.net/api/login',
                method: 'POST',
                data: {
                    username: username,
                    password: password
                }

            }).then(res => {
                console.log(res);
                alert('登录成功')
            }).catch(err => {
                alert('账号或密码错误,登录失败')
                console.log(err);
            })
        })
    </script>
</body>

</html>

七.业务状态码


成功(2XX)

状态码 原因短语 说明

200 OK 表示从客户端发来的请求在服务器端被正确处理

201 Created 请求已经被实现,⽽且有⼀个新的资源已经依据请求的需要⽽建⽴ 通常是在 POST 请求,或是某些 PUT 请求之后创建了内容, 进行的返回的响应

202 Accepted 请求服务器已接受,但是尚未处理,不保证完成请求 适合异步任务或者说需要处理时间比较长的请求,避免 HTTP 连接一直占用

204 No content 表示请求成功,但响应报⽂不含实体的主体部分

206 Partial Content 进⾏的是范围请求, 表示服务器已经成功处理了部分 GET 请求 响应头中会包含获取的内容范围 (常用于分段下载)


重定向(3XX)

状态码 原因短语 说明

301 Moved Permanently 永久性重定向,表示资源已被分配了新的 URL 比如,我们访问 http://www.baidu.com 会跳转到 https://www.baidu.com

302 Found 临时性重定向,表示资源临时被分配了新的 URL, 支持搜索引擎优化 首页, 个人中心, 遇到了需要登录才能操作的内容, 重定向 到 登录页

303 See Other 对于 POST 请求,它表示请求已经被处理,客户端可以接着使用 GET 方法去请求 Location 里的 URI。

304 Not Modified 自从上次请求后,请求的网页内容未修改过。 服务器返回此响应时,不会返回网页内容。(协商缓存)

307 Temporary Redirect 对于 POST 请求,表示请求还没有被处理,客户端应该向 Location 里的 URI 重新发起 POST 请求。

不对请求做额外处理, 正常发送请求, 请求 location 中的 url 地址

因为 post 请求, 是非幂等的, 从 302 中, 细化出了 303 和 307

简而言之:

  • 301 302 307 都是重定向

  • 304 协商缓存


客户端错误(4XX)

状态码 原因短语 说明

400 Bad Request 请求报⽂存在语法错误(传参格式不正确)

401 UnAuthorized 权限认证未通过(没有权限)

403 Forbidden 表示对请求资源的访问被服务器拒绝

404 Not Found 表示在服务器上没有找到请求的资源

408 Request Timeout 客户端请求超时

409 Confict 请求的资源可能引起冲突


服务端错误(5XX)

状态码 原因短语 说明

500 Internal Sever Error 表示服务器端在执⾏请求时发⽣了错误

501 Not Implemented 请求超出服务器能⼒范围,例如服务器不⽀持当前请求所需要的某个功能, 或者请求是服务器不⽀持的某个⽅法

503 Service Unavailable 表明服务器暂时处于超负载或正在停机维护,⽆法处理请求

505 Http Version Not Supported 服务器不⽀持,或者拒绝⽀持在请求中使⽤的 HTTP 版本

八.问答机器人

完成效果图


核心代码

<!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>17-19.案例_问答机器人</title>
    <link rel="stylesheet" href="https://unpkg.com/reset.css@2.0.2/reset.css" />
    <script src="./js/axios.js"></script>
    <style>
        body {
            margin: 0;
            font-family: 'Microsoft YaHei', sans-serif;
        }

        .wrap {
            position: absolute;
            width: 100%;
            height: 100%;
            overflow: hidden;
        }

        .header {
            height: 55px;
            background: linear-gradient(90deg, rgba(246, 60, 47, 0.6), rgba(128, 58, 242, 0.6));
            overflow: hidden;
        }

        .header h3 {
            color: #faf3fc;
            line-height: 55px;
            font-weight: normal;
            float: left;
            letter-spacing: 2px;
            margin-left: 25px;
            font-size: 18px;
            text-shadow: 0px 0px 5px #944846;
        }

        .header img {
            float: right;
            margin: 7px 25px 0 0;
            border-radius: 20px;
            box-shadow: 0 0 5px #f7f2fe;
        }

        .main {
            position: absolute;
            left: 0;
            right: 0;
            top: 55px;
            bottom: 55px;
            background-color: #f4f3f3;
            box-sizing: border-box;
            overflow: hidden;
        }

        .talk_list {
            width: 100%;
            height: 100%;
            overflow-y: auto;
        }

        .talk_list li {
            overflow: hidden;
            margin: 20px 0px 30px;
            display: flex;
        }

        .talk_list .left_word {
            justify-content: flex-start;
        }

        .talk_list .left_word img {
            margin-left: 20px;
            width: 44px;
            height: 44px;
        }

        .talk_list .left_word span {
            background-color: #fe9697;
            padding: 10px 15px;
            border-radius: 12px;
            font-size: 16px;
            color: #fff;
            margin-left: 15px;
            margin-right: 20px;
            position: relative;
            line-height: 24px;
        }

        .talk_list .left_word span:before {
            content: '';
            position: absolute;
            left: -8px;
            top: 12px;
            width: 13px;
            height: 12px;
            background: url('../img/corner01.png') no-repeat;
        }

        .talk_list .right_word {
            justify-content: flex-end;
        }

        .talk_list .right_word img {
            margin-right: 20px;
            width: 44px;
            height: 44px;
        }

        .talk_list .right_word span {
            background-color: #fff;
            padding: 10px 15px;
            border-radius: 12px;
            font-size: 16px;
            color: #000;
            margin-right: 15px;
            margin-left: 20px;
            position: relative;
            line-height: 24px;
        }

        .talk_list .right_word span:before {
            content: '';
            position: absolute;
            right: -8px;
            top: 12px;
            width: 13px;
            height: 12px;
            background: url('../img/corner02.png') no-repeat;
        }

        .footer {
            width: 100%;
            height: 55px;
            left: 0px;
            bottom: 0px;
            background-color: #fff;
            position: absolute;
            display: flex;
            align-items: center;
            padding: 0 10px;
            box-sizing: border-box;
        }

        .input_txt {
            height: 37px;
            border: 0px;
            background-color: #f4f3f3;
            border-radius: 8px;
            padding: 0px;
            margin: 0 10px;
            outline: none;
            text-indent: 15px;
            flex: 1;
        }

        .input_sub {
            width: 70px;
            height: 37px;
            border: 0px;
            background-color: #fe9697;
            margin: 0;
            border-radius: 8px;
            padding: 0px;
            outline: none;
            color: #fff;
            cursor: pointer;
        }
    </style>

</head>

<body>
    <div class="wrap">
        <!-- 头部 Header 区域 -->
        <div class="header">
            <h3>小思同学</h3>
            <img src="lib/img/person01.png" alt="icon" />
        </div>
        <!-- 中间 聊天内容区域 -->
        <div class="main">
            <ul class="talk_list" style="top: 0px;" id="talk_list">
                <!-- 机器人 -->
                <li class="left_word">
                    <img src="lib/img/person01.png" /> <span>嗨,最近想我没有?</span>
                </li>
                <!-- 我 -->
                <li class="right_word">
                    <img src="lib/img/person02.png" /> <span>想,想你教我写代码!</span>
                </li>
            </ul>
        </div>
        <!-- 底部 消息编辑区域 -->
        <div class="footer">
            <img src="lib/img/person02.png" alt="icon" />
            <input type="text" placeholder="说的什么吧..." class="input_txt" id="ipt" />
            <input type="button" value="发 送" class="input_sub" id="btnSend" />
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/axios@0.27.2/dist/axios.min.js"></script>
    <script>
        // 需求:完成和机器人聊天效果
        const talk_list = document.querySelector('#talk_list')
        document.querySelector('#btnSend').addEventListener('click', function () {
            // 1.获取用户的输入框的值(内容)
            const words = document.querySelector('#ipt').value.trim()

            const li = document.createElement('li')

            li.className = 'right_word'
            li.innerHTML = `<img src="lib/img/person02.png" /> <span>${words}</span>`

            talk_list.appendChild(li)

            // 让滚动条滚到最下面

            talk_list.scrollTop = talk_list.scrollHeight



            // 发送消息之后情况输入框的内容
            document.querySelector('#ipt').value = ''
            // 2.发ajax
            axios({
                url: 'http://ajax-api.itheima.net/api/robot',//开启这个关掉下面的url开启机器人狂暴版,尝试着和它对着骂吧!!!
                // url: 'http://ajax-base-api-t.itheima.net/api/robot',
                method: 'GET',
                // 传递的参数
                params: {
                    spoken: words
                }
            }).then(res => {
                console.log(res.data.data.info.text);

                const li = document.createElement('li')

                li.className = 'left_word'
                li.innerHTML = `<img src="lib/img/person01.png" /> <span>${res.data.data.info.text}</span>`

                document.querySelector('#talk_list').appendChild(li)
                // 让滚动条滚到最下面

                talk_list.scrollTop = talk_list.scrollHeight
            })

        })



        // // 目标: 完成和机器人聊天效果
        // // 目标: 完成和机器人聊天效果
        // // 明确目标和效果演示
        // // 1. 准备标签和样式
        // let ipt = document.querySelector('#ipt')
        // let btnSend = document.querySelector('#btnSend')
        // let ul = document.querySelector('#talk_list')

        // // 2. 绑定事件, 获取用户聊天消息
        // btnSend.addEventListener('click', function () {
        //     let content = ipt.value // 获取我说的消息并铺设到页面
        //     let newLi = document.createElement('li')
        //     newLi.className = 'right_word'
        //     newLi.innerHTML = `
        //                 <img src="lib/img/person02.png" /> <span>${content}</span>
        //               `
        //     ul.appendChild(newLi)
        //     ul.scrollTop = ul.scrollHeight // 并让滚动条滚动到底部

        //     // 点击发送按钮清除输入框的内容
        //     ipt.value = ''

        //     // 3. 基于axios发送给服务器换回机器人消息
        //     axios({
        //         url: 'http://ajax-api.itheima.net/api/robot',
        //         method: 'GET',
        //         // params对应查询参数(query)
        //         // data对应请求体数据(body)
        //         params: {
        //             spoken: content
        //         }
        //     }).then(({ data: res }) => {

        //         // 4. 把消息铺设到页面上
        //         console.log(res) // 服务器响应回来的数据
        //         let text = res.data.info.text // 存机器人说的话
        //         let leftLi = document.createElement('li')
        //         leftLi.className = 'left_word'
        //         leftLi.innerHTML = `
        //                     <img src="lib/img/person01.png" /> <span>${text}</span>
        //                    `
        //         ul.appendChild(leftLi)

        //         // 5. 让滚动条始终在底部
        //         ul.scrollTop = ul.scrollHeight
        //     })
        // })
    </script>
</body>

</html>

最后自测一下选择题看看自己学废了吗?


Ajax初识自测选择题



版权声明:本文为Moraxz原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。