Ajax响应JSON数据到页面(koa框架)

2021-05-12  本文已影响0人  似朝朝我心

如何响应JSON数据到页面?

如果服务端可以响应JSON数据到浏览器端,那么我们就可以通过Ajax拿到服务端响应给浏览器端的数据,拿到这个JSON数据后,我们就可以响应到页面中。

响应JSON数据到页面的三种形式:

DOM操作方式

DOM操作是HTML文档的编程接口。DOM将文档解析为一个由节点和对象组成的结果济河,也叫DOM树。简而言之,它会将Web页面和脚本语言连接起来使用。

常见的DOM操作API:createElement、append、prepend、before、after、remove

案例:

前端代码:

    <body>
        <table border="1" cellspacing="" cellpadding="">
            <thead>
                <tr>
                    <th>姓名</th>
                    <th>年龄</th>
                    <th>性别</th>
                </tr>
            </thead>
            <tbody>

            </tbody>
        </table>
        <script type="text/javascript">
            //DOM操作
            let tbody = document.querySelector('tbody')

            //Ajax请求
            let xhr = new XMLHttpRequest()
            xhr.onload = function() { //onload事件,服务器请求已经完成
                if (xhr.status == 200) {
                    //console.log(xhr.responseText) //获取响应的JSON数据
                    const data = JSON.parse(xhr.responseText) //解析拿到的JSON数据
                    //console.log(data.userList)

                    //DOM操作方法1:遍历JSON数据渲染到页面
                    // for(let i = 0;i < data.userList.length;i++){
                    //  let tr = document.createElement('tr')   
                    //      for(let attr in data.userList[i]){
                    //          let td = document.createElement('td')
                    //          console.log(data.userList[i][attr])
                    //          td.innerHTML = data.userList[i][attr]
                    //          tr.append(td)
                    //  }
                    //      tbody.append(tr)
                    // }

                    //DOM操作方法2:遍历JSON数据渲染到页面
                    for (let item of data.userList) {
                        //console.log(item)
                        let tr = document.createElement('tr')
                        for (let index in item) {
                            let td = document.createElement('td')
                            //console.log(item[index])
                            td.innerHTML = item[index]
                            tr.append(td)
                        }
                        tbody.append(tr)
                    }
                }
            }
            xhr.open('GET', '/userInfo', true)
            xhr.send()
        </script>
    </body>

后端代码

router.get('/userInfo', async (ctx ,next) => {
    console.log(ctx.request.query)
    ctx.body = {
        errCode: 0,
        errMsg: 'ok',
        userList: [
            {
                "userName":"苏列",
                "age":21,
                "gender":"男"
            },
            {
                "userName":"张三",
                "age":23,
                "gender":"男"
            },
            {
                "userName":"宋岚",
                "age":20,
                "gender":"女"
            }
        ]
    }
})

页面渲染效果:



ES6模板字符串拼接语法的操作方式

模板字符串使用反引号(``)来代替普通字符中用双引号和单引号,可以使用多行字符串和字符串的插值、拼接变量、添加H5标签功能,非常方便灵活。



案例:(只需将上面的前端代码作修改即可,服务端代码不用动)

    <body>
        <table border="1" cellspacing="" cellpadding="">
            <thead>
                <tr>
                    <th>姓名</th>
                    <th>年龄</th>
                    <th>性别</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
        <script type="text/javascript">
            //DOM操作
            let tbody = document.querySelector('tbody')
            //Ajax请求
            let xhr = new XMLHttpRequest()
            xhr.onload = function() { //onload事件,服务器请求已经完成
                if (xhr.status == 200) {
                    const data = JSON.parse(xhr.responseText) //解析拿到的JSON数据
                    //模板字符串拼接:
                    tbody.innerHTML = data.userList.map((item,i) => { //map遍历一步到位
                        console.log(item,i)
                        return `
                            <tr>
                                <td>${item.userName}</td>
                                <td>${item.age}</td>
                                <td>${item.gender}</td>
                            </tr>
                        `
                    }).join('')
                }
            }
            xhr.open('GET', '/userInfo', true)
            xhr.send()
        </script>
    </body>

页面渲染效果:



采用前端模板引擎进行改写方式,分离页面部分和逻辑实现部分,也就是现在的vue和react都借鉴的思想

模板引擎可以让(网站)程序实现界面和数据分离,使业务代码和逻辑代码分离开来,提升开发效率,这种模板引擎的设计,提高了代码的复用。

比较流行的前端模板引擎框架:
art-template、mustache、ejs、Handlebars.js、jQuery tmpl等...


安装art-template模板引擎

npm install art-template --save

安装完成后,打开依赖包 node_modules 找到art-template这个模块下,而我们需要的仅仅是template-web.js这个脚本文件,可以在script标签中单独引入使用。



复制一份放到koa框架下。



脚本引入
<script src="./javascripts/template-web.js" type="text/javascript" charset="utf-8"></script>

使用了模板引擎的前端代码:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <script src="./javascripts/template-web.js" type="text/javascript" charset="utf-8"></script>
    </head>
    <body>
        <table border="1" cellspacing="" cellpadding="">
            <thead>
                <tr>
                    <th>姓名</th>
                    <th>年龄</th>
                    <th>性别</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
        
        <!-- 模板引擎 -->
        <script id="tpl-tbody" type="text/html">
            {{each userList}}
            <tr>
                <td>{{$value.userName}}</td
                <td>{{$value.age}}</td>
                <td>{{$value.gender}}</td>
            </tr>
            {{ /each }}
            <!--{{ each userList }} ..... {{ /each }} 代表遍历循环开始和结束,可以看作标签 -->
        </script>
        
        <script type="text/javascript">
            //DOM操作
            let tbody = document.querySelector('tbody')
            //Ajax请求
            let xhr = new XMLHttpRequest()
            xhr.onload = function() { //onload事件,服务器请求已经完成
                if (xhr.status == 200) {
                    const data = JSON.parse(xhr.responseText) //解析拿到的JSON数据
                    tbody.innerHTML = template('tpl-tbody',data) //将拿到的data放入模板,然后渲染页面
                }
            }
            xhr.open('GET', '/userInfo', true)
            xhr.send()
        </script>
    </body>
</html>

预览:


效果

总结:


前面我们已经知道并实现了如何响应数据给浏览器,那浏览器是怎么发送JSON数据给服务端呢,让请求体携带JSON?显然这GET方式不可行,因为它不能携带发送JSON数据。

POST请求发送JSON数据

POST请求需要通过修改请求头信息,进行JSON数据的发送,通过serRequestHeader()方法进行设置。

请求头类型Content-Type需要设置为application/json
需要通过JSON.stringfy()转义JSON数据


案例:

前端代码:

        <script type="text/javascript">
            const xhr = new XMLHttpRequest()
            xhr.onload = function() {
                console.log('服务器请求完成')
            }
            xhr.open('POST','/userInfo',true)
            xhr.setRequestHeader('Content-Type','application/json')
            xhr.send(JSON.stringify({"userName":"秦明","age":21}))
        </script>

服务器代码:

router.post('/userInfo', async (ctx ,next) => {
    console.log(ctx.request.body) //通过request对象下的body进行接收
    ctx.body = 'userInfo'
})

Network控制台查看


POST状态,200成功

请求头信息



携带的JSON数据

再来看看后端有没有拿到浏览器POST过来的JSON数据。



总结:

上一篇 下一篇

猜你喜欢

热点阅读