Flask实战第52天:cms添加轮播图前端代码逻辑完成

首页我们在模态框中的保存按钮加一个id,这样方便我们选取这个按钮

<button type="button" class="btn btn-primary" id="save-banner-btn">保存</button>

在static/cms/js/下新建banners.js

$(function () {
    $("#save-banner-btn").click(function (event) {
        event.preventDefault();
        var dialog = $("#banner-dialog");
        var nameInput = dialog.find("input[name='name']");
        var imageInput = dialog.find("input[name='image_url']");
        var linkInput = dialog.find("input[name='link_url']");
        var priorityInput = dialog.find("input[name='priority']");

        var name = nameInput.val();
        var image_url = imageInput.val();
        var link_url = linkInput.val();
        var priority = priorityInput.val();

        if(!name || !image_url || !link_url || !priority){
            zlalert.alertInfoToast('请输入完整的轮播图数据!');
            return;
        }

        bbsajax.post({
            "url": '/cms/abanner/',
            "data": {
                'name':name,
                'image_url': image_url,
                'link_url': link_url,
                'priority':priority,
            },
            'success': function (data) {
                dialog.modal("hide");
                if(data['code'] == 200){
                    // 重新加载这个页面
                    window.location.reload();
                }else{
                    zlalert.alertInfo(data['message']);
                }
            },
            'fail': function () {
                zlalert.alertNetworkError();
            }
            
        });
    });
});

编辑cms.view.py中的banners视图, 获取数据库数据

@bp.route('/banners/')
@login_required
def banners():
    banners = BannerModel.query.order_by(BannerModel.priority.desc()).all()
    return render_template('cms/cms_banners.html', banners=banners)

编辑cms_banners.html, <tbody>中的内容动态展示

        <tbody>
            {% for banner in banners %}
                <tr>
                    <td>{{ banner.name }}</td>
                    <td><a href="{{ banner.image_url }}" target="_blank">{{ banner.image_url }}</a></td>
                    <td><a href="{{ banner.link_url }}" target="_blank">{{ banner.link_url }}</a></td>
                    <td>{{ banner.priority }}</td>
                    <td>{{ banner.create_time }}</td>
                    <td>
                        <button class="btn btn-default btn-xs edit-banner-btn">编辑</button>
                        <button class="btn btn-danger btn-xs delete-banner-btn">删除</button>
                    </td>
                </tr>
            {% endfor %}
        </tbody>

然后在cms_banners.html中引入banners.js

{% block head %}
    <script src="{{ url_for('static', filename='cms/js/banners.js')}}"></script>
    ...
{% endblock %}

这样,我们添加轮播图的功能就完成了,现在可以加轮播图试试

 

posted @ 2018-08-30 22:13  sellsa  阅读(691)  评论(0编辑  收藏  举报