ajax的使用案例-新闻列表的渲染

学习ajax使用的一个小案例
主要功能:通过ajax请求后端数据,然后将数据渲染到页面中。
主要代码:
1.首先引入template-web.js,对template进行管理

  <script src="javascripts/template-web.js"></script>

2.发送通过ajax网络请求,获取数据

<script>
        let ul = document.querySelector('.sports-list');
        let xhr = new XMLHttpRequest();
        xhr.onload = function() {
    
    
            if (xhr.status == 200) {
    
    
                // console.log(xhr.responseText);
                let data = JSON.parse(xhr.responseText);
                if (data.errcode == 0) {
    
    
                    ul.innerHTML = template('tpl-sports', data)
                }
            }
        }
        xhr.open('POST', '/list', true);
        xhr.setRequestHeader('Content-Type', 'application/json');
        xhr.send(JSON.stringify({
    
    
            "page": 0,
            "count": 10
        }))
    </script>

3.编写后端代码,对ajax进行数据响应(router/index.js)

//引入fs模块
const fs = require('fs')
router.post('/list', async(ctx, next) => {
    
    
    // console.log(cxt.request.body);
    //规定参数的类型为number
    let args = [
        {
    
     field: 'page', type: 'number' },
        {
    
     field: 'count', type: 'number' }
    ]
    //接收传入的数据
    
    let body = ctx.request.body;
    for (let i = 0; i < args.length; i++) {
    
    
        let item = args[i];
        //判断传入的参数个数
        if (!Object.keys(body).includes(item.field)) {
    
    
            ctx.body = {
    
    
                errcode: -1,
                errmsg: "参数个数错误"
            };
            return;
        } else {
    
    
            //判断参数的类型
            if (typeof body[item.field] != item.type) {
    
    
                ctx.body = {
    
    
                    errcode: -2,
                    errmsg: "参数类型错误"
                };
                return;
            }
        }
    }
    //通过node中fs模块打开json文件
    let data = fs.readFileSync('./data/list.json');
    //将json数据转换为对象形式
    data = JSON.parse(data);
    //截取数据,从页数x个数的乘积截取count个
    let list = data.splice(body.page * body.count, body.count)
    ctx.body = {
    
    
        errcode: 0,
        errmsg: 'ok',
        list
    }
})

4.将数据显示到页面上

 <script id='tpl-sports' type='text/html'>
        {
    
    {
    
    each list}}
        <li>
            <div class="sports-list-text">
                <p>{
    
    {
    
    $value.title}}</p>
                <p>
                    <span>{
    
    {
    
    $value.comment}}</span></span>
                </p>
            </div>
            <div class="sports-list-img">
                <img src="{
    
    {$value.img}}" alt="">
            </div>
        </li>
        {
    
    {
    
    /each}}
    </script>

实现效果
在这里插入图片描述全部代码:
index.html

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
    
    
            margin: 0;
            padding: 0;
        }
        
        ul,
        ol {
    
    
            list-style: none;
        }
        
        img {
    
    
            display: block;
        }
        
        #sports-header {
    
    
            width: 100%;
            height: 50px;
            background: #537bff;
            display: flex;
            justify-content: space-between;
            align-items: center;
            color: white;
            font-size: 20px;
            padding: 0 10px;
            position: fixed;
            top: 0;
            z-index: 100;
        }
        
        #sports-main {
    
    
            margin-top: 50px;
            height: calc(100vh - 50px);
        }
        
        #sports-main ul {
    
    
            background: white;
        }
        
        #sports-main ul li {
    
    
            display: flex;
            border-bottom: 1px #f7f7f7 solid;
            margin: 0 18px;
            padding: 20px 0;
        }
        
        #sports-main .sports-list-text {
    
    
            flex: 1;
            font-size: 18px;
            line-height: 26px;
        }
        
        #sports-main .sports-list-text p:last-of-type {
    
    
            font-size: 14px;
            color: #828c9b;
            display: flex;
            margin-top: 10px;
        }
        
        #sports-main .sports-list-text p:last-of-type span {
    
    
            margin-right: 10px;
        }
        
        #sports-main .sports-list-img {
    
    
            width: 130px;
            margin-left: 20px;
        }
        
        #sports-main .sports-list-img img {
    
    
            width: 100%;
            border-radius: 10px;
        }
        
        #loadingDown {
    
    
            width: 100%;
            position: absolute;
            top: 60px;
            z-index: -1;
            text-align: center;
        }
        
        #loadingUp {
    
    
            width: 100%;
            text-align: center;
            padding: 20px 0;
        }
        
        #loading {
    
    
            position: absolute;
            left: 0;
            top: 0;
            right: 0;
            bottom: 0;
            margin: auto;
            width: 200px;
            height: 30px;
            line-height: 30px;
            text-align: center;
            z-index: 100;
        }
    </style>
    <script src="javascripts/template-web.js"></script>
    <script src="javascripts/axios.js"></script>
    <script src="javascripts/better-scroll.js"></script>
</head>

<body>
    <header id="sports-header">
        腾讯 | 体育
    </header>
    <div id="loadingDown"></div>
    <main id="sports-main">
        <div>
            <ul class="sports-list">

            </ul>
            <div id="loadingUp"></div>
        </div>
        <div id="loading"></div>
    </main>
    <script id='tpl-sports' type='text/html'>
        {
    
    {
    
    each list}}
        <li>
            <div class="sports-list-text">
                <p>{
    
    {
    
    $value.title}}</p>
                <p>
                    <span>{
    
    {
    
    $value.comment}}</span></span>
                </p>
            </div>
            <div class="sports-list-img">
                <img src="{
    
    {$value.img}}" alt="">
            </div>
        </li>
        {
    
    {
    
    /each}}
    </script>
    <script>
        let ul = document.querySelector('.sports-list');
        let xhr = new XMLHttpRequest();
        xhr.onload = function() {
    
    
            if (xhr.status == 200) {
    
    
                // console.log(xhr.responseText);
                let data = JSON.parse(xhr.responseText);
                if (data.errcode == 0) {
    
    
                    ul.innerHTML = template('tpl-sports', data)
                }
            }
        }
        xhr.open('POST', '/list', true);
        xhr.setRequestHeader('Content-Type', 'application/json');
        xhr.send(JSON.stringify({
    
    
            "page": 0,
            "count": 10
        }))
    </script>
</body>

</html>

router/index.js

const router = require('koa-router')()
const fs = require('fs')
router.get('/', async(ctx, next) => {
    
    
    await ctx.render('index', {
    
    
        title: 'Hello Koa 2!'
    })
})

router.get('/string', async(ctx, next) => {
    
    
    ctx.body = 'koa2 string'
})

router.get('/json', async(ctx, next) => {
    
    
        ctx.body = {
    
    
            title: 'koa2 json'
        }
    })
    // ctx 请求上下文
router.get('/list', async(ctx, next) => {
    
    
    // 接收查询字符串传入的数据
    console.log(ctx.request.query);
    // ctx.body = 'list data'
    ctx.body = {
    
    
        errcode: 0,
        errmsg: 'ok',
        list: [
            {
    
     'username': "lm", "age": "33" },
            {
    
     'username': "ml", "age": "13" },
            {
    
     'username': "lm", "age": "33" }
        ]
    }
})

router.post('/list2', async(ctx, next) => {
    
    
    // 接收查询字符串传入的数据
    console.log(ctx.request.body);
    ctx.body = 'list2 data'
})

router.post('/list', async(ctx, next) => {
    
    
    // console.log(cxt.request.body);
    let args = [
        {
    
     field: 'page', type: 'number' },
        {
    
     field: 'count', type: 'number' }
    ]
    let body = ctx.request.body;

    for (let i = 0; i < args.length; i++) {
    
    
        let item = args[i];
        if (!Object.keys(body).includes(item.field)) {
    
    
            ctx.body = {
    
    
                errcode: -1,
                errmsg: "参数个数错误"
            };
            return;
        } else {
    
    
            if (typeof body[item.field] != item.type) {
    
    
                ctx.body = {
    
    
                    errcode: -2,
                    errmsg: "参数类型错误"
                };
                return;
            }
        }
    }
    let data = fs.readFileSync('./data/list.json');
    data = JSON.parse(data);

    let list = data.splice(body.page * body.count, body.count)
    ctx.body = {
    
    
        errcode: 0,
        errmsg: 'ok',
        list
    }
})
module.exports = router

猜你喜欢

转载自blog.csdn.net/weixin_57399180/article/details/118075069