首页 > 用ajax和undersc.js结合来渲染页面时,显示datas未定义,请大神帮忙看看吧

用ajax和undersc.js结合来渲染页面时,显示datas未定义,请大神帮忙看看吧

我想在移动端通过点击按钮来加载更多内容,我的思路是通过ajax获取数据后,用underscore.js中的模板方法来把这些数据渲染到页面,但总是显示datas is not undefined,代码如下

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>click loadmore</title>
    <style type="text/css">
        .box{
            width: 300px;
            padding: 20px;
            background-color: #FF3366;
            margin: 20px auto;
            color: #fff;
            border-radius: 5px;
        }
        .btn{
            width: 600px;
            margin: 0 auto;
            background-color: #e3e3e3;
            padding: 20px 0;
            text-align: center;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <!-- data unit -->
    <div class="container">
        <div class="box">this start</div>
    </div>
    <div class="btn">加载更多</div>
    <script type="text/template" id="tpl">
        <% _.each(datas, function(item){ %>
            <div class="box"> <%= item.name %> </div>
        <% }); %>
    </script>
    <script type="text/javascript" src="js/jquery-1.12.1.js"></script>
    <script type="text/javascript" src="js/underscore.js"></script>
    <script type="text/javascript">
            // 渲染首页首次加载的部分数据
            var htmlStr = '';
            for(var i=0; i<5; i++){
                htmlStr += '<div class="box">this' + i +'</div>';
            }
            $('.container').append(htmlStr);
            $('.btn').click(function(){
                // var theDatas;
                $.ajax({
                    type: 'post',
                    url: './data02.json',
                    success: function(datas){
                        console.log(datas);
                        $('.container').append(_.template( $('#tpl').html(), datas ));
                    }
                });
            });
    </script>
</body>
</html>

因为不知道你的underscore版本,先把这句话改了试试:

$('.container').append(_.template($('#tpl').html())({ datas: datas }));

补充:

underscore文档:template

【热门文章】
【热门文章】