Flask + Ajax + Mysql 实现网页异步加载(二)

Flask + Ajax + Mysql 实现网页异步加载(一)

二、jquery 和Ajax 实现前端请求

<script src="static/js/jquery.min.js"  >
</script>

<script type="text/javascript">
    var pk = 1;
    $(window).scroll(function () {
        //下面这句主要是获取网页的总高度,主要是考虑兼容性所以把Ie支持的documentElement也写了,这个方法至少支持IE8
        var htmlHeight = $(document).height();
        //clientHeight是网页在浏览器中的可视高度,
        var clientHeight = $(window).height();
        //scrollTop滚动条到顶部的垂直高度
        var scrollTop = $(document).scrollTop();
        //通过判断滚动条的top位置与可视网页之和与整个网页的高度是否相等来决定是否加载内容;
        var he = scrollTop + clientHeight;
        if (he == htmlHeight ) {
            pk = pk +1; //每次和后端交互,page+1。
            addListMore();
        }
        if (scrollTop <=0){
            refresh();
        }
        //console.log("滚动条位置:" + scrollTop);
        //console.log("可视高度:" + clientHeight);
        //console.log("网页总高度" + htmlHeight);
    });
    function addListMore() {
        //console.log("加载更多");
        $.ajax({
            type:"GET",
            url:"/?page="+pk,
            dataType:"html",
            success:function (data) {
                //var $data = $(data);
                //var target_div = $data.find("#div1");
                //$("body").append(target_div);
                $("#div2").empty();
                var div = document.createElement("div");
                document.body.appendChild(div);
                div.innerHTML = data;

            }

        })
    }
    function refresh() {
        $.ajax({
            type:"GET",
            url:"/",
            dataType:"html",
            success:function () {
                window.location.reload();
                //location.href = url + "/teacherList";


            }
        })

    }
</script>

主要有三个问题:

1、判断滚动位置+可视高度=网页总高度。

2、如何改变url的page参数.

3、ajax 的success:function(data){ }    如何把服务器端发送过来的html加载到当前页面的后面。   

var div = document.createElement("div");
document.body.appendChild(div);
div.innerHTML = data;

    这三句实现了把data,也就是返回的index.html 作为div显示在当前网页上。

猜你喜欢

转载自blog.csdn.net/qq_34333481/article/details/83896751